Home > Enterprise >  how can I represent tuple as a 2D array in python?
how can I represent tuple as a 2D array in python?

Time:11-18

Imagine a NxN chess board, I have a tuple t = (0,3,2,1) which represents chess pieces location at each column (col = index), and each number represents the row, starting at 0 from bottom.

For this example, it has 4 columns, first piece is at row=0 (bottom row), second piece is on row=3 (fourth/highest row), third piece is on row=2 (third row from bottom), fourth piece is on second row from bottom.

I would like to represent it as a 2D array as follows:

[[0,1,0,0],
 [0,0,1,0],
 [0,0,0,1],
 [1,0,0,0]]

I was able to generate the 2D array using this code

pieces_locations = (0,3,2,1)
pieces_locations = list(pieces_locations)

table_size = len(pieces_locations)

arr = [[0 for col in range(table_size)] for row in range(table_size)]

However, I was not able to assign the 1's in their correct locations.

I was able to understand this: arr[row][col], but the rows are inverted (0 is top to N is bottom).

CodePudding user response:

Use this after you've made the list (A matrix of 0s) ** If the locations list is not as long as the number of rows, the program will crash (use try and except to counter)

for x, i in enumerate(range(1, len(arr))):
    arr[-i][pieces_locations[x]] = 1

This should give you your desired output, I hope this helps

CodePudding user response:

First create the 2-d list of zeroes.

arr = [[0] * table_size for _ in range(table_size)]

Then loop over the locations, replacing the appropriate elements with 1.

for col, row in enumerate(pieces_location, 1):
    arr[-row][col] = 1

CodePudding user response:

I was able to figure it out, although I'm sure there is a move convenient way.

pieces_locations = (0,3,2,1)
pieces_locations = list(pieces_locations)

table_size = len(pieces_locations)

arr = [[0 for col in range(table_size)] for row in range(table_size)]


for row in range(0, table_size):
        arr[row][pieces_locations.index(row)] = 1


res = arr[::-1]
print (res)
  • Related