Skip to content Skip to sidebar Skip to footer

How To Not Repeat Randint Value

I just wrote a code to generate random numbers and try to match it with random numbers, but I don't know how to not repeat the randint value, can someone help me? from random impor

Solution 1:

Simplest may be:

deck = list(range(1, 10001))
random.shuffle(deck)

and use deck.pop() to get the next "randint without repetition".

This is pretty much how you get a random card without repetition from a deck (which indeed the very name of random.shuffle suggests, and why I called the variable deck:-): you start with all cards in the deck, shuffle the deck once (thoroughly of course!-), then just deal the last card from the top of the deck each time, without putting it back in the deck.


Solution 2:

Riffing off Alex's solution, if you don't want to maintain a list of arbitrary length (for example, if you want a few hundred unique random ints in the range (0..a gazillion), then you instead have to maintain a list of numbers that have been chosen already:

numbers = set()
while len(numbers) < enough:  # enough is defined somewhere...
  numbers.add (random.randint(0, upper_limit))

Post a Comment for "How To Not Repeat Randint Value"