0

I’d like to have a random card from a shoe. I have the following code :

s = 4
deck = {'2':4*s,'3':4*s, '4':4*s,'5':4*s, '6':4*s,'7':4*s, '8':4*s,'9':4*s, '10':4*s,'J':4*s, 'Q':4*s,'K':4*s, 'A':4*s}

def newCard(player):
    card=random.choice(deck.keys())
    player.append(card)
    deck[card]-=1

But I don’t know how to implement the probability depending of the number of the cards still in the deck. How can I do that ?

Shan-x
  • 1,146
  • 6
  • 19
  • 44

1 Answers1

0

Thanks to the comment of andrew cooke, I have a working solution :

def weighted_random(deck):
    total = sum(deck.values())
    r = randint(1, total)
    for c in deck.keys():
        r -= deck[c]
        if r <= 0:
            deck[c]-=1
            return c

results = weighted_random(deck)
Shan-x
  • 1,146
  • 6
  • 19
  • 44