0

I'm trying to refactor some logic that I have in a script of mine, which used to be a bunch of nested IF statements.

It will essentially iterate through a user-chosen column (pick) of a 2D array to find an empty value (denoted by a period placeholder here) and insert a symbol depending on a certain condition.

next((x for x in board[x][pick] if board[x][pick] != "."), fullCols.append(pick))
board[x][pick] = symbol

On the first line, it will fail because it will say list index out of range. The 2D array was initialized to seven columns and six rows.

Any help?

3 Answers 3

3
  1. Don't reuse the symbol x in your generator expression when you're also indexing your board with it. This is the likely proximate cause of your error.

  2. I don't know why your append statement is being used as the default argument to next.

  3. I don't know what is in your array, but board[x][pick] != "." implies that board[x][pick] is expected to be a string which means that x for x in board[x][pick] will be iterating through characters which doesn't sound like what you described.

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

1 Comment

1. How else would I look through the 2D array to find the first non-filled value? 2. It is meant to append the column to a list called fullCols if the column is full. 3. I wanted to iterate through the values, not the characters.
0

You are using x as a loop variant while also using the same x to reference the board iterable. This means the value of variable x is dependent on itself (since it is dependent on board[x][pick]). For what you are trying to achieve a better way might be using numpy arrays or pandas dataframes or if you need to use python 2-D arrays then explicitly looping over the column while keeping the row constant so something like:

for i in range(numrows):
  next((x for x in board[i] if board[i][pick] != "."),...

Comments

0

I think you want to find the symbol if it exists in the column called pick, and set it to symbol. If not, you want to add the column to a list of full columns. I'm pretty sure this is wrong, because that doesn't explain what you would do with respect to the pick if the column is full. Nevertheless:

EMPTY = '.'
rows = [row for row in board if row[pick] == EMPTY]
if rows:
    rows[0][pick] = symbol
else:
    fullCols.append(pick)
    print("Whatcha gonna do now?")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.