Python 'break' behaves unexpectedly

时间:2016-07-11 20:27:41

标签: python string loops substring break

People who have given an interview test maybe familiar with the "substring" question. The question is, as follows:

"For string find the largest substring from the right that has at most two different characters.

I have written a small code to achieve this:

def generate_substring(givenstring):
    givenstring_list = []

    for i in range(0, len(givenstring)):
        for j in range(0, len(givenstring)):
            if i != j:
                givenstring_list.append(givenstring[i:j])

    return_list = [givenstring_list[i] for i in range(0,len(givenstring_list)) if givenstring_list[i] != '']

    return reversed(return_list)


def main():
    code_input = raw_input("Enter a string: ")
    substrings_list = generate_substring(code_input)
    temp = ""

    for substrings in substrings_list:
        for i in range(1, len(substrings)):
            if substrings[i - 1] != substrings[i]:
                temp = substrings
                break #Notice This!

    print(temp)


main()

Notice the for loop with a break. I don't know why is this, but break cannot manage to break out of the loop. Therefore I get the leftmost substring instead. Why is that?

0 个答案:

没有答案