Charan
Charan

Reputation: 1081

while loop not breaking, cannot find the bug

Beginner here.Something is wrong with my code. While loop is not terminating. Where did I go wrong?

def check( x ):  # x is defaultdict(list) 
    a = sorted(x , reverse=True)
    j = 0
    while (j<len(a)):
        c = d[a[j]] # current list
        l = len(c) # current list length
        m = 0
        while (m<l) :
            if c[m] == m or c[m] == n-1-m :
                continue
            else:
                return "No"
            m = m + 1
        j = j + 1
    return "Yes"

Upvotes: 0

Views: 71

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90869

I am guessing this is the issue -

while (m<l) :
    if c[m] == m or c[m] == n-1-m :
        continue

Lets assume , we have a value where c[m] is equal to m . You just continue the while loop, without changing m (or c , though I am guessing c is not to be changed) , so the next time, it comes back to this condition , again c[m] is equal to m , since neither of them have changed, and again you do continue to continue the loop. And this goes on forever.

continue statement does not execute the rest of the while loop, it continues on with the next iteration of the loop.

I think you want to increment m even when the condition is true? , If so try something like -

while (m<l) :
    if c[m] != m and c[m] != n-1-m :
        return "No"
    m = m + 1

I am not sure if there are any other issues in your code, since we really do not know what its supposed to be doing.

Upvotes: 3

Kartal Kaan Bozdoğan
Kartal Kaan Bozdoğan

Reputation: 375

It seems like the "continue" statement causes the infinite loop by skipping the "m = m + 1" line

Upvotes: 2

Related Questions