'python giving me "TypeError: list indices must be integers or slices, not tuple" and i cant figure out why
i have this code:
board = [[1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0], [1, 0, 1, 1, 0, 0], [1, 0, 0, 0, 0, 1]]
def print_board():
for line in board:
for char in line:
print(char, end=" ")
print()
print_board()
island_list = []
for y in range(len(board)):
for x in range(len(board[y])):
if board[y][x] == 1:
if (y, x) not in island_list:
if x == len(board[x]) - 1 or x == 0 or y == len(board)-1 or y == 0:
island_list.append((y, x))
List_to_add = []
for y in range(len(board)):
state = 0
for x in range(len(board[0])):
if board[y][x] == 1 and (y, x) not in island_list or state == 1 and (y, x) not in island_list:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []
if (y, x) in island_list and board[y][x] == 1 or state == 1:
for x in List_to_add:
island_list.append(x)
List_to_add = []
for x in range(0, len(board[0])):
state = 0
for y in range(0, len(board)):
if state == 1:
for x in List_to_add:
island_list.append(x)
if board[y][x] == 1:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []
print(island_list)
in this program im trying to seperate the indexes that are connected to the edges of the matrix from the ones not connected but when i try to access an index in the matrix
im getting the TypeError for line 46: if board[y][x] == 1:.
i find this really weird as i used this same exact statement in a line above this one and got no error.
would appreciate some help with this issue.
Solution 1:[1]
When you are running loop
for x in range(0, len(board[0])):
state = 0
for y in range(0, len(board)):
if state == 1:
for x in List_to_add:
island_list.append(x)
if board[y][x] == 1:
List_to_add.append((y, x))
if (y, x) in island_list:
state = 1
if board[y][x] == 0:
state = 0
List_to_add = []
check line
for x in List_to_add:
in this line you are using x as temporary variable which at the end reinitialise x with a tuple thus creating a problem for you.
Just rename this variable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepak Tripathi |
