Jan-21-2021, 09:56 AM
My intention is to populate a 2d array with booleans at a certain DENSITY. Although the function "populate" seems to do the right thing up to exiting a double for loop, it seems as if the last row of the array has been stored in all rows, as shown in the output
from array import * import random MAXHORZ = 15 MAXVERT = 10 DENSITY = 50 torus = array('b') torus = [[0] * MAXHORZ] * MAXVERT def populate_torus(torus): for x in range(MAXVERT): for y in range(MAXHORZ): if random.randint(1, 100) < DENSITY: torus[x][y] = 1 else: torus[x][y] = 0 print(torus[x]) print() for i in range(MAXVERT): print(torus[i]) return(torus) def display_torus(torus): print('In Display:') for x in range(0, MAXVERT): print(torus[x]) print('end') torus = populate_torus(torus) display_torus(torus) print('DONE')The output produced is as follows:
Output:/usr/bin/python3.8 /tmp/first_run.txt/Torus.py
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
[0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0]
[0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1]
[1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0]
[1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0]
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0]
[1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
In Display:
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0]
end
DONE
Process finished with exit code 0
There is obviously something I do not understand about arrays can anyone spot the flaw for me>
buran write Jan-21-2021, 09:53 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.