vendredi 14 février 2020

Python - Construction of a two-dimensional list of random integers, shows repetition, that should not be there [duplicate]

i am fairly new to python, and this is the first hurdle i came across. Here is what's happening:

from random import randint

empty = [[0]*9]*9

def randomboard():
  board = empty
  for x in range(0,8):
    for y in range(0,8):
      nextInt = randint(0,29) - 20
      #nextInt = 0 if nextInt < 0 else nextInt
      board[x][y] = nextInt
  return board

def printboard(board):
  for x in range(0,8):
    print(board[x])
  print("----")

printboard(empty)
printboard(randomboard())

The Output is the following:

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

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

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

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

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

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

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

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


[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]


What the Code should do: Create an Empty 9x9 board. Fill it with random values. Then print the result.

As you can see, the first axis keeps repeating, even though i feel like this should not be the case and i can only try to fathom why it is. Here are a couple of possibilities:

-The RNG Seed resets after every iteration of the first loop: I wouldn't even know what to do in this case, and it would seem very unintuitive for this to happen.

-I have been doing something weird during the construction of the random list.Possibly some false syntax, that i have been taking over from java: I have been looking into other code examples, and the code snippet still seems good to me. Maybe i'm not seeing something, that you do.

-The printboard function just prints the first row over and over: I already tried to substitute the funtion for "print(board)", but that also returns the repeating list.

-Something totally different, that i have been overlooking

At this point, i'd really appreciate your help.

Thank you in advance!




Aucun commentaire:

Enregistrer un commentaire