ocean.1234
ocean.1234

Reputation: 127

Python function output error, Checking an index to see value?

I am building a function that accepts a puzzle= 2d list and checks to make sure every position has a value in it. If it has none in it, then it needs to return false. It should be pretty basic but my function keeps returning True and I cannot understand why.

Example input/expected output:

is_complete([[1,2,3],[3,1,2],[2,3,1]]) → True

is_complete([[None,None],[None,None]]) → False

My code is as follows:

def is_complete(puzzle):
    for row in puzzle:
        for val in row:
            if val == None:
                return False
            else:
                return True

Upvotes: 2

Views: 77

Answers (2)

Rolo787
Rolo787

Reputation: 370

Your function will immediately stop after either return statement. This is why it will return False if the only value passed is '[[None]]'. A solution to this would be to move your 'return True' after all values have been iterated over.

def is_complete(puzzle):
    for row in puzzle:
        for val in row:
            if val == None:
                return False
    return True

Upvotes: 2

avlec
avlec

Reputation: 394

A solution that seems to work with your test input and even with the '[[None]]' as mentioned by Rolo787 is as follows. Instead of using 2 for loops, just check if None is in the row.

def is_complete(puzzle):
    for row in puzzle:
        if None in row:
            return False
    return True

Upvotes: 1

Related Questions