import random
def main():
values = [
[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]
]
for r in range(5):
for c in range(5):
rand = random.randint(1, 25)
if values[r][c] != rand:
values[r][c] = rand
for i in range(5):
print("\n")
for j in range(5):
print("\t" str(values[i][j]), end=" ")
main()
This code should've printed a 5 x 5 matrix with a range of 1-25 without repeating the number. For some reason, the if command I did put in did not randomize it. Can someone help me with the solution?
CodePudding user response:
Try this:
from random import shuffle
numbers = list(range(1, 26))
shuffle(numbers)
values = [[numbers[i * 5 j] for j in range(5)] for i in range(5)]
First you create a list of numbers from 1 to 25. Then you randomly shuffle it. And finally you create a matrix out of it.
CodePudding user response:
I interpret the question as not having any number appear more than once in the matrix? The following is to clarify my understanding.
import random
def main():
values = [
[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]
]
for r in range(5):
for c in range(5):
rand = random.randint(1, 25)
# Modify with while loop to ensure number appears only once.
if values[r][c] != rand:
values[r][c] = rand
for i in range(5):
print("\n")
for j in range(5):
print("\t" str(values[i][j]), end=" ")
main()
Output not desired because for example 4 and 13 appear more than once?
20 5 12 11 14
14 20 25 4 4
11 18 22 13 8
22 18 12 13 13
20 1 19 23 17