Home > Net >  While loop and if statements
While loop and if statements

Time:11-14

I have a string and k = number, which is the length of a substring that has the same letter repeated in a row. How can I have the wanted output only? The expected output: For length 3, found the substring ddd!

my_string = 'aabadddefggg'
k = 3
x = 1
c = 1
while x < len(my_string):
    if my_string\[x\] == my_string\[x-1\]:
        c  = 1
    else:
        c = 1
    if c == k:
        print("For length  "   str(k)   ", found the substring "   my_string\[x\] \* k   "!")
        break
    else:
        print("Didn't find a substring of length "   str(k))
        break
    x  = 1
The output: 
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
For length  3, found the substring ddd!

CodePudding user response:

get rid of the break after didnt find the string. Your code means that once you evaluate c == k you will always break beacuse you have the break in both the if and the else meaning you can never reach x = 1

my_string = 'aabadddefggg'
k = 3
x = 1
c = 1
while x < len(my_string):
    if my_string[x] == my_string[x-1]:
        c  = 1
    else:
        c = 1
    if c == k:
        print("For length  "   str(k)   ", found the substring "   my_string[x] * k   "!")
        break
    else:
        print("Didn't find a substring of length "   str(k))
    x  = 1

OUTPUT

Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
For length  3, found the substring ddd!

CodePudding user response:

Even better, put your else statement under the while, this way:

my_string = 'aabadddefggg'
k = 3
x = 1
c = 1
while x < len(my_string):
    if my_string[x] == my_string[x-1]:
        c  = 1
    else:
        c = 1
    if c == k:
        print("For length  "   str(k)   ", found the substring "   my_string[x] * k   "!")
        break
    x  = 1
else:
    print("Didn't find a substring of length "   str(k))

# For length  3, found the substring ddd!

With k = 4 (the else statement is executed if the end of the loop is reached, which happens only if it doesn't break out of it):

# Didn't find a substring of length 4
  • Related