Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number except numbers written in list before

I know how to get random numbers from, for example, 7 to 14, but is it also possible to somehow get random Numbers from 7 to 14 except some numbers from a list written before?

Example:

Forbidden = [12, 13, 8, 7]
a = randint(7, 14) 

a should be a random number but not the numbers written in Forbidden.

Edit: Thanks for the advice, using a while loop or .choice actually solved my Problem. But at the end @user2357112 was right, obviously the Blacklist Idea is a Beginner trap, shuffling a deck solved my Problem.

like image 526
Raccoon Avatar asked Nov 25 '25 13:11

Raccoon


1 Answers

You know how a real card game prevents you from drawing cards that have already been drawn? It doesn't involve a blacklist of drawn cards. There's a deck, and you shuffle it.

Do the same thing in your program. Instead of trying to maintain a blacklist of drawn cards, shuffle a deck of cards at the start of the program and draw cards from the deck:

import random

deck = some_list
random.shuffle(deck)

# when you want to draw a card
card = deck.pop()
like image 134
user2357112 supports Monica Avatar answered Nov 28 '25 01:11

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!