Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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).

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading