Reputation: 25
I am asking the program to print out the numbers 1 through 9 in a random order, in a grid. The problem is that when it prints out, it will have the same numbers twice. Here is the code that I have so far:`import random rows = 3 cols = 3
values = [[0,0,0]]
for r in range(rows):
for c in range(cols):
values [r][c] = random.randint(1, 9)
print(values)
`
and an example output:
[[6, 0, 0]]
[[6, 4, 0]]
[[6, 4, 2]]
also, those double brackets are annoying. any way to fix that?
Upvotes: 0
Views: 106
Reputation: 882781
Use random.shuffle
to randomize the order of the numbers you want:
import random
numbers = list(range(1, rows * cols + 1)) # good for Py 2 *and* 3
random.shuffle(numbers)
values = [[0] * cols for r in rows]
(the latter to avoid duplicates in values
and make it the right size -- I don't see how your original code could fail to raise exceptions!).
then:
for r in range(rows):
for c in range(cols):
values[r][c] = numbers(r + rows * c)
print(values[r])
which also removes the double brackets (assuming you want single ones) and only prints each row once (your original indentation would print the whole matrix many, many times:-).
Upvotes: 2
Reputation: 845
If you don't mind using numpy, try numpy.random.shuffle()
.
Example:
import numpy
xx = numpy.arange(10)
numpy.random.shuffle(xx)
print xx
Upvotes: 0