Home > Software engineering >  New to python! Can anyone explain why does this loop not work
New to python! Can anyone explain why does this loop not work

Time:06-25

I want to iterate through the list test_board for each element and see whether it matches the value "X" or "O" if it does then the function should reproduce it as True, else false. But despite my changing the elements of the list the result nonetheless comes out as True.

test_board = ['#', 'X', 'L', 'X', 'O', 'X', 'O', 'X', 'O', 'X']

def full_board_check(board):
    for i in range(1,10):
        if board[i] in ["X","O"]:
            return True
    return False

CodePudding user response:

Here is a more idiomatic way:

def full_board_check(board):
    return all(el in ["X", "O"] for el in board[1:])

for el in board[1:] will iterate over each element (not index) in the bord, starting with the second one. I usually prefer this iteration over board[i], because you can pick a name, e.g. for letter in "abc".

The rest is just list comprehension (I would recommend to give this concept a look) and then using all to validate your list of booleans.

CodePudding user response:

From this code, when there is a "X" or "O" it will return True instantly. But in your case, you want to check if there is something that doesn't match those two. You can switch the logic:

def full_board_check(board):
    for i in range(1,10):
        if board[i] not in ["X","O"]:
            return False
    return True

I'm assuming that you want to check whether the board is valid. In this code, it loops for each element, if there is something that is not "X" or "O", it will return False. Otherwise, if it is still not returned yet, return True.

To make the code a little bit better, you can use the list element instead of the list index.

def full_board_check(board):
    for i, element in enumerate(board):
        if i == 0 and element != "#":
            return False
        elif element not in ["X","O"]:
            return False
    return True

Update: I added a condition to except "#" in first element.

CodePudding user response:

If you want to check each element and get result for every of them you should use function like this:

def full_board_check(board):
    result_list = []
    for element in board:
        if element not in ["X","O"]:
            result_list.append(False)
        else: result_list.append(True)
    return result_list

CodePudding user response:

Just reversed if condition and .find method. If any of given characters is not in the list ["X", "O"] then False - otherwise every element will be checked and if ok return True

def full_board_check(board=['A', 'X', 'L', 'X', 'O', 'X', 'O', 'X', 'O', 'X']):
    for i in range(len(board)):
        if 'X, O'.find(board[i]) == 0:
            return False

    return True
  • Related