1

I'm working on a bingo card, but I cannot seem to generate different numbers using randint. This time it may have all different numbers in b, but the next time, it has a couple duplicate numbers.

How do I make it so it generates different numbers without duplicates?

Thanks.

import random

class Card:
    def __init__(self):
        self.b = []
        self.i = []
        self.n = []
        self.g = []
        self.o = []

        for x in range(0, 5):
            r = random.randint(1, 15)
            self.b.append(r)

        print(self.b)
        print(self.i)
        print(self.n)
        print(self.g)
        print(self.o)

p = Card()
Alec
  • 919
  • 2
  • 10
  • 25
  • Aside: rather than having five variables, one for each letter, you should use a `dict`. DRY (don't repeat yourself) is a very useful principle to follow, as violations of it are often a sign that you're working at the wrong level of abstraction. – DSM Mar 16 '13 at 22:44

5 Answers5

5

From this answer

self.b = random.sample(range(1, 16), 5)
Community
  • 1
  • 1
Ric
  • 8,615
  • 3
  • 17
  • 21
2

How about his:

while len(self.b) < 5:
  r = random.randint(1, 15)
  if not r in self.b:
    self.b.append(r)
piokuc
  • 25,594
  • 11
  • 72
  • 102
1

If you're choosing five random integers between 1 and 15, you're liable to get a few duplicates. You can try selecting without replacement instead:

self.b = random.sample(range(1,16),5)
Karmel
  • 3,452
  • 2
  • 18
  • 11
0

In addition to the sample in random, you can use choice function which is new in numpy 1.7.0 if you have it:

from numpy import random
self.b = list(random.choice(range(1,16), size=5, replace=False))

The advantage of it is that it takes an optional parameter p involving the probabilities associated with each entry in the population. This is uniform in your case which is the default one.

petrichor
  • 6,459
  • 4
  • 36
  • 48
0

You can use np.random.shuffle which modifies the array in place

>>> a = np.arange(1,16)
>>> np.random.shuffle(a)
>>> a[0:5]
array([ 9, 11,  7,  4, 10])
>>> np.random.shuffle(a)
array([ 3,  1, 13,  5,  8])

So maybe something like

>>> class Card:
      def __init__(self,arr):
        np.random.shuffle(arr)
        self.b = arr[0:5]
        #etc

>>> nums = np.arange(1,16)
>>> p = Card(nums)
>>> p.b
array([ 8,  2,  6, 13,  9])
dermen
  • 5,252
  • 4
  • 23
  • 34