Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading