简体   繁体   中英

IndexError: string index out of range doesn't make sense

I have a problem that i can't explain, I'm making a program to find the "longest common prefix" and I got an error IndexError: string index out of range.

I noticed that changing the order on an if statement was the solution, but that doesn't make sense for me.

This line was:

if default[j] == list[i][j] and j < len(default):

The solution to the problem is:

    if j < len(default) and default[j] == list[i][j]:

Why does this happen, isn't it the same? Am I blind?

This is the code with the error:

list=["hola", "holo", "holi"]
default=list[0]

for i in range(1, len(list)):
    temp=""
    if len(default)==0:
        break;

    for j in range(len(list[i])):
        if default[j] == list[i][j] and j < len(default):
            temp+=default[j]
        else:
            break

    default=temp
print(default)

Order matter when using and operator.

a and b

If a is true then only b is checked. It doesn't matter if b consist of an error (except syntax error).

The two statements are not the same.

if we have a condition statement

if Condtion1 and Condetion2:

Conditon2 will be checked if and only if Condtion1 is True.

Let us examine the folowing short examples, and it will be clear:

a=10
b=0
if b!=0 and a/b>3:
   print('Do Something')
else:
   print('ok')

The output will be ok

But, if we reorder the condtions in if statement if a/b>3 and b:=0:

a=10
b=0
if a/b>3 and b!=0:
   print('Do Something')
else:
   print('ok')

The later code give error ZeroDivisionError: division by zero , where, a/b was examined first and the fact the b is equal to 0.

But, in the first code, the conditon b,=0 was examined first, and gives False , so the second condition a/b>3 was not processed.

So, the two statements are not the same.

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