Repeated random numbers

I created a bingo game where random numbers are generated and called for a list.

bingo_num = random.randint(1,100)

How to stop a random number generated more than once

+3
source share
7 answers

Just do it the same way they do it in a real bingo game. They do not roll the dice, but put all the numbers in a large bag, shake it and pull out the numbers one at a time until all the numbers are exhausted.

numbers = list(range(1, 101)) # all the numbers in the bag, from 1 to 100
random.shuffle(numbers)       # shake the bag
bingo_num = numbers.pop()     # pull out next number (inside your loop)
+2
source

I would suggest random.shuffle

from random import shuffle
my_list = range(100)
shuffle(my_list)
print my_list

But if you need only a certain number of unique numbers, you can use random.sample, for example

from random import sample
my_list = range(100)
print sample(my_list, 10)
+4
source

sample

>>> import random
>>> nums = random.sample(range(0,200),100)
>>> nums
[143, 149, 52, 183, 161, 179, 180, 155, 163, 157, 139, 15, 154, 181, 56, 29, 31,
 14, 77, 82, 165, 32, 35, 92, 109, 172, 69, 99, 54, 3, 88, 76, 11, 126, 78, 162,
 198, 145, 124, 75, 114, 174, 136, 100, 190, 193, 148, 153, 167, 113, 38, 17, 16
8, 0, 196, 73, 47, 164, 184, 6, 140, 30, 58, 74, 4, 79, 147, 178, 191, 21, 112,
13, 27, 57, 199, 116, 28, 104, 111, 71, 23, 85, 170, 25, 141, 156, 91, 7, 182, 1
34, 94, 169, 175, 166, 137, 160, 129, 36, 67, 135]
+3

, . , , , .

For example, if you want to have 5 different numbers from 0-9:

possible_numbers = range(10)
numbers = []

for i in range(5):
    index = random.randint(0, len(possible_numbers) - 1)
    numbers.append(possible_numbers[index])
    del possible_numbers[index]
+1
source

Something like this should work:

numbers = []
while len(numbers) < 100:
    bingo_num = random.randint(1,100)

    if not bingo_num in numbers:
        numbers.append(bing_num)
0
source

You can simply create a new number if it is already in use

advantage: simple code

Drawback: it will work for a long time if almost all numbers are used (there are better solutions)

Code example:

bingo_num_list = []

# init num
bingo_num = random.randint(1,100)

# create new numbers till "find" a not used one
while bingo_num in bingo_num_list:
    bingo_num = random.randint(1,100)

bingo_num_list.append(bingo_num)
0
source

Make a list of all numbers, then select random 1, remove it from the list and select the following:

#!/usr/bin/python
import random

myNumz=[]
xIdx=1
while xIdx<101:
myNumz.insert(xIdx,xIdx)
    xIdx+=1

xIdx=100
while xIdx>0:
    xIdx-=1
    baseNum=random.randint(0,xIdx)
    print myNumz[baseNum]
    myNumz.remove(myNumz[baseNum])
0
source

All Articles