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

Question:

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:

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)
Asked By: Verpanther

||

Answers:

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
Answered By: Yash Mehta
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.