Randint does not generate random numbers the second time I use it
My randint when used the second time it does not generate new random numbers, it remains with the same numbers generated. I know that in C when this happens I can use srand (time (NULL)); , but in Python I'm not finding anything like
Show 3 different arrays
from random import randint
matriz = [[], [], []]
def gerar_matriz ():
for c in range(len(matriz)):
for i in range(0, 3):
s = randint(0, 9)
matriz[c].append(s) # adiciona os números a matriz
for c in range(3):
gerar_matriz()
for c in range(len(matriz)):
for i in range(0, 3):
print(matriz[c][i], end=' ')
print(' ')
print ('\n')
1 answers
The problem is that you are not creating new arrays on each call to gerar_matriz()
- what you do is add new numbers to the end of each already existing line.
And at the time of printing the lines, you used a fixed size of 3, so you always see the first three elements of the line.Just change your internal print for to see what's going on:
...
for c in range(len(matriz)):
for i in range(0, len(matriz[0])): # alterei esta linha
print(matriz[c][i], end=' ')
print(' ')
Why Good programming practices in general ask us to do everything within functions-your code that creates a new array and that calls the array generation is out of functions and cannot be executed in such a way as to isolate the array, which is a global variable.
If you do this, it will work:
from random import randint
def gerar_matriz ():
matriz = [[], [], []]
for c in range(len(matriz)):
for i in range(0, 3):
s = randint(0, 9)
matriz[c].append(s) # adiciona os números a matriz
return matriz
def imprime():
for c in range(3):
matriz = gerar_matriz()
for c in range(len(matriz)):
for i in range(0, 3):
print(matriz[c][i], end=' ')
print(' ')
print ('\n')
imprime()
All I did there was stop relying on The "Matrix" as a global variable - it is created inside the generar_matrix function and returned to whoever called the function. (turning the print code into a function is not essential, but prevents the "array" name from being re-named associated globally, and that other functions would see only the last Matrix generated).
Another thing is that in Python you rarely, rarely even have to use for
with range
. In general, we are interested in the elements of a sequence, not in the indices of the elements, and then look for the elements.
In the case of the array, we can do a for
to get each row, and inside a for
to get each element:
def imprime():
for c in range(3): # aqui sim, queremos repetir algo 3 vezes!
matriz = gerar_matriz()
for linha in matriz:
for elemento in linha:
print(elemento, end=' ')
print()
print ('\n')