Home > OS >  Need to print the first occurrence of k-size subsequence, but my code prints the last
Need to print the first occurrence of k-size subsequence, but my code prints the last

Time:11-13

You are given a string my_string and a positive integer k. Write code that prints the first substring of my_string of length k all of whose characters are identical (lowercase and uppercase are different). If none such exists, print an appropriate error message (see Example 4 below). In particular, the latter holds when my_string is empty.

Example: For the input my_string = “abaadddefggg”, k = 3 the output is For length 3, found the substring ddd! Example: For the input my_string = “abaadddefggg”, k = 9 the output is Didn't find a substring of length 9

this is my attempt:

my_string = 'abaadddefggg'
k = 3
s=''
for i in range(len(my_string) - k   1):
    if my_string[i:i k] == my_string[i] * k:
        s = my_string[i:i k]
if len(s) > 0:
    print(f'For length {k}, found the substring {s}!')
else:
    print(f"Didn't find a substring of length {k}")

CodePudding user response:

You need break. When you find the first occurrence you need to exit from the for-loop. You can do this with break. If you don't break you continue and maybe find the last occurrence if exists.

my_string = 'abaadddefggg'
k = 3
s=''

for i in range(len(my_string) - k   1):
    if my_string[i:i k] == my_string[i] * k:
        s = my_string[i:i k]
        break
        
if len(s) > 0:
    print(f'For length {k}, found the substring {s}!')
else:
    print(f"Didn't find a substring of length {k}")

You can use itertools.groupby and also You can write a function and use return and then find the first occurrence and return result from the function.

import itertools

def first_occurrence(string, k):
    for key, group in itertools.groupby(string):
        lst_group = list(group)
        if len(lst_group) == k:
            return ''.join(lst_group)
    return ''

my_string = 'abaadddefggg'
k = 3
s = first_occurrence(my_string, k)
if len(s) > 0:
    print(f'For length {k}, found the substring {s}!')
else:
    print(f"Didn't find a substring of length {k}")

CodePudding user response:

One alternative approach using an iterator:

my_string = 'abaadddefggg'

N= 3

ou = next((my_string[i:i N] for i in range(len(my_string)-N)
           if len(set(my_string[i:i N])) == 1), 'no match')

Output: 'ddd'

  • Related