tags:

views:

127

answers:

4

I want to choose 10 random integers from 0 to 99. I know I can use:

random.randint(a, b)

But how to tell the randint() that I only want different integers.

Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like an optimal solution.

+9  A: 
from random import sample

sample(range(0, 100), 10)
Vincent Savard
If you want to use a large range, you can use `xrange`, as mentioned in [the docs](http://docs.python.org/library/random.html#random.sample), to avoid allocating a huge list of numbers that you don't care about.
intuited
Just always use `xrange` here. It's hard to think of any reason to ever use `range` in this case.
Glenn Maynard
@Glenn Maynard : Python 3 ?
Vincent Savard
@Fayden: `range` in Python 3 *is* Python 2's `xrange`.
Glenn Maynard
I know, which is why I said this. I use Python 3, therefore there is no reason for me to use xrange! But I entirely get your point, we should use xrange in Python 2.
Vincent Savard
That is why I typically add the following in the start of my modules who have to be used under both Python 2 and 3: `try: xrange; except NameError: xrange= range` (change `;` to `\n` of course)
ΤΖΩΤΖΙΟΥ
+7  A: 

Here's general strategy that is language independent. Generate an array of 100 entries from 0 to 99. Choose a random number from 0 to 99 and swap the entry at that position with the element at position 0. Then successively choose a random number from i to 99, where i = 1 to 9 and swap the element at that position with the one at element i. Your 10 random numbers are in the first 10 positions of the array.

tvanfosson
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
LukeH
@LukeH - thanks for the reference. This is, indeed, a variant of the Fisher-Yates in-place shuffle.
tvanfosson
+1  A: 

This may not be a solution depending on what you will need to use this for... but have you thought of splitting it off into 10 different random number generators? Ex. 0-9, 10-19, 20-29, etc. I guess that's not really as "random" as you are specifying different ranges and are guaranteed 1 number from each range. The only other solution I can think of would be to have a list of the random integers, iterate through and check to see if the random number has been generated yet and if so run the random.randint() again.

Sarkis Varozian
I like tvanfosson's solution below better than my solution.
Sarkis Varozian
A: 

Here is a language independent solution:

integer numbers[10];
for(integer i = 0; i < 10; i += 1) {
    integer num = randomInteger(min = 0, max = (99 - i));
    boolean hasFoundDuplicate = false;
    for(integer j = 0; j < i && hasFoundDuplicate == false; j += 1) {
        if(numbers[j] == num) {
            num = 99 + 1 - i + j;
            hasFoundDuplicate = true;
        }
    }
    numbers[i] = num;
}
potatis_invalido