Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}")

>Solution :

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 a, b in itertools.groupby(string):
        lst_b = list(b)
        if len(lst_b) == k:
            return ''.join(lst_b)
    return ''

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading