1

I am trying to make a card game and I want to be able to generate random numbers in a list but I do not want the numbers to repeat themselves after they have been used once while the program is running.

Here is what I have so far:

usedcards = []
import random

def choosecards():
    global usedcards
    cards=random.sample(range(52), 5)
    usedcards = usedcards + cards
    #print(usedcards)
    return cards

Each time I run the function, I want the usedcards list to be cross checked with the cards variable.

How can I make this happen?

1
  • 3
    Just make a list of available cards, shuffle it (random.shuffle()) and .pop() a card when you need one. Commented Jan 12, 2016 at 23:55

3 Answers 3

4

Here is one way to do this using sets. Sets make it very easy to exclude the cards that have already been used.

import random

used_cards = set()

def choose_cards(n_cards):
    # No need to do 'global used_cards', used_cards is
    #    already global and can be modified inplace
    # Find the set difference between all the cards and
    #   those that have been used
    available = set(range(52)) - used_cards
    chosen = random.sample(available, n_cards)
    for card in chosen:
        used_cards.add(card)
    return chosen


for i in range(4):
    print(choose_cards(5))
    print(used_cards)
Sign up to request clarification or add additional context in comments.

1 Comment

you can also use used_cards.update(chosen) to avoid the for-loop
3

A generator can keep the state and hide the details:

import random

def choosecards(amount=5):
    cards = list(range(52))
    random.shuffle(cards)
    while True:
        yield [cards.pop() for _ in range(amount)]


>>> cards = choosecards()
>> next(cards)
[37, 41, 13, 2, 33]
>>> next(cards)
[4, 8, 7, 38, 23]

Comments

2

don't use globals. The problem becomes easy to solve if you use parameters properly.

def choosecards(stack, amount=5):
    cards=[ stack.pop() for i in range(amount) ]
    return cards


deck = list(range(52))
random.shuffle(deck)
hand = choosecards(deck)
otherhand = choosecards(deck)
#etc.

1 Comment

I think you mean stack.pop()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.