This Python code to check if there is 007 order in a list does not work

Question:

a=[1,2,0,0,7,11]
flag=0
flag1=0
for i in range(0,len(a)):
    if a[i]==0:
        flag=1
    elif flag==1 and a[i]==0:
        flag1=1
    elif flag==1 and flag1==1 and a[i]==7:
        print(True)
    else:
        pass

This is one of the problem in udemy. Returns True if there is an order of 007.
MY OUTPUT:
BLANK OUTPUT

Asked By: Kanishka.R

||

Answers:

This is because for second 0, the elif flag==1 and a[i]==0: will not be executed but the if a[i]==0: will be executed. So, for first 0, flag will be set to 1 and for the second 0, the if a[i]==0 will again be true. As a result, the flag will be again set to 1 without executing the desired elif block. You may want to change the if block like below –

if flag==0 and a[i]==0:

That way when flag is set to 1 once, the if block will not be executed but the elif will be executed. So, the whole code will be –

for i in range(0,len(a)):
    if flag==0 and a[i]==0:
        flag=1
    elif flag==1 and a[i]==0:
        flag1=1
    elif flag==1 and flag1==1 and a[i]==7:
        print(True)
    else:
        pass

Btw, if your code needs to check if 007 comes in order without any number in between them, then this code will also not work.

Answered By: kuro

elif is never executed.

What about this:

if all(True if i in a else False for i in [0,0,7]):
    print(True)
Answered By: Colonel Mustard
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.