简体   繁体   中英

How do you I get the value differently while looping for common prefix?

strs = ["cir","car"]
#strs = ["flower","flow","flight"]
def get_min_str(lst):
    return min(lst, key=len)
str1 = get_min_str(strs)

lens = len(strs)
x = ""
mlen = len(str1)

if(lens == 1):
    print(strs[0])

for i in range(0, mlen):
    for j in range(0, lens-1):

       

        if( strs[j][i] == strs[j+1][i] ):
            if(j == lens-2):
                x = x +  strs[j][i]
            print(strs[j][i])
        else:
            break
        print(strs[j][i] == strs[j+1][i])
            
       


print(x)

                    

      

So in order to find the longest common prefix, I have used two loops. To loop over the values. But in the example, strs = ["cir","car"]. I should the value x = "c" but I stead get the value "cr", since I have used the break function. The function should have stopped at c. Why isn't it?Why do I get the value "cr" your text

Since you have two nested loops, the break keyword only exits the inner loop. Then, the third letter matches, so r is added to x . To fix this, set a variable when you should exit the outer loop and check it before each iteration.

Edit: also, for readability's sake, you may want to explore the enumerate() function, which converts an iterable (like a string) into an iterable of tuples of the form (index, value) , so your code could look like:

should_break = False

for letter_index, current_character in enumerate(str1):
    if should_break:
        break
    for str_index in range(0, lens):
        if strs[str_index][letter_index] != current_character:
            should_break = True  # set break condition for outer loop
            break  # break from inner loop
    else:   # executed when the for loop doesn't break
        x += current_character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM