7

I've tried a few approaches, none of which seem to work for me.

board = [[0,0,0,0],[0,0,0,0]]

if not 0 in board:
     # the board is "full"

I then tried:

if not 0 in board[0] or not 0 in board[1]:
    # the board is "full"

None of these approaches worked, though the second one generally let the array fill up more. (I wrote code to fill up the array randomly).

2
  • 1
    What exactly do you mean by "did not work"? Commented Jul 16, 2018 at 20:39
  • The # the board is full was (for lack of a better word) run at the wrong time. Commented Jul 16, 2018 at 20:40

4 Answers 4

11

You need to iterate over all the indices of your list to see if an element is a value in one of the nested lists. You can simply iterate over the inner lists and check for the presence of your element, e.g.:

if not any(0 in x for x in board):
    pass  # the board is full

Using any() will serve as a short-stop whenever it encounters an element with a 0 in it so you don't need to iterate over the rest.

Sign up to request clarification or add additional context in comments.

1 Comment

why use 1 and put a condition in your generator expression? Just put the condition as the value: any(0 in x for x in board)
4

I will try to address what you did wrong:

if not 0 in board[0] or not 0 in board[1]: this is almost right - but you should use and because to be considered full, both boards must not have 0 at the same time.

Some options:

if not 0 in board[0] and not 0 in board[1]: # would work

if 0 not in board[0] and 0 not in board[1]: # more idiomatic

if not(0 in board[0] or 0 in board[1]): # put "not" in evidence, reverse logic

if not any(0 in b for b in board): # any number of boards

Comments

1

Another try with chain from itertools (that way it works with multiple rows):

from itertools import chain

board = [[0,0,0,0],[0,0,0,0]]

def find_in_2d_array(arr, value):
    return value in chain.from_iterable(arr)

print(find_in_2d_array(board, 0))
print(find_in_2d_array(board, 1))

Prints:

True
False

Comments

1

If you can use tool outside the standard library numpy is the best way to work with multidimensional arrays by a long way.

board = [[0,0,0,0],[0,0,0,0]]
board = np.array(board)
print(0 in board)

Output:

True

2 Comments

I would like to keep my program as lightweight as possible. Are there any major advantages to using numpy as opposed to some of the other single lines others have proposed?
It really depends on what operations you're using, but I'd say in general you get a speed up with numpy compared to using a loop in python. Also the syntax is super flexible for indexing, i.e. returning the i'th row would be board[:, i].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.