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

Why this solution to codewars challenge is taking so much time that it gets 'Execution Timed Out'?

I’m new to programming in python so I don’t know why this solution is not effective
Code:

def check(seq, elem):
    i=0
    b=0
    while i<len(seq):
        while (b==0):
            if (seq[i]==elem):
                b=1
                i+=1
                return(True)
        else:
            return(False)

Problem: link

EDIT:
Thanks to one comment I spotted infinite loop but still it is not effective and I don’t know why
EDITED CODE:

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

def check(seq, elem):
    i=0
    b=0
    while (b==0) and (i<len(seq)):
        if (seq[i]==elem):
            b=1
            i+=1
            return(True)
    else:
        return(False)

>Solution :

Testcases: like check([1,2,3],4) your code will go into infinite loop. {when ele not present in list it will tends to infinite}

Optimization. you can do by single for/while loop only.

Code:

def check(seq, elem):
    for num in seq:
        if num == elem:
            return True
    return False
            
print(check([1,2,3],4)) #False

Code:

def check(seq, elem):
    i=0
    while i < len(seq):
        if seq[i] == elem:
            return True
        i += 1
    return False
print(check([1,2,3],4)) #False
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