0

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?

Jesse
  • 25
  • 1
  • 7

2 Answers2

2

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:-).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Accepting the answer (clicking on the green checkmark outline to the answer's left) is always the best way to express thanks (as soon as enough time has passed since your question to let you accept, of course:-)... – Alex Martelli Feb 15 '15 at 22:35
  • just did it as soon as i could! – Jesse Feb 15 '15 at 22:38
  • That was an accident on the other one, sorry. I also found that other answer peculiar. And I couldn't get it to work the exact way I wanted, but I just wanted to thank you that you provided some help. It helped provide a different look at things and I could tell that it was a good and well thought out answer. The problem I have is a little too complicated to ask on here I think, unfortunately :( – Jesse Feb 16 '15 at 00:17
  • @Jesse, pity! Do recall that if you don't want **all** of the numbers 1 to N, but just X of them in random order w/o repetitions, `random.sample` is your friend -- just in case that's part of your other complications!-) – Alex Martelli Feb 16 '15 at 01:29
0

If you don't mind using numpy, try numpy.random.shuffle().

Example:

import numpy
xx = numpy.arange(10)
numpy.random.shuffle(xx)
print xx
dslack
  • 835
  • 6
  • 17