Python Forum

Full Version: how do i pass duplicates in my range iterator?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
this is the code that randomly picks a card from deck:
import collections

Card = collections.namedtuple('Card', ['rank', 'suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits
                                        for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]

from random import choice
deck = FrenchDeck()

for i in range(10):
    print(choice(deck))
I'm not sure I understand. Are you trying to avoid duplicates when getting random cards at the end? If so, I would random.shuffle() instead, and then pop() cards off the deck.
I'm really a novice at python; I'm actually a C# programmer can you show me how?
random.shuffle(self._cards) will shuffle the list of cards in place. That is, it will put them in a random order. self._cards.pop() will remove and return the last item in the list (the top card on the deck, so to speak). You don't get duplicates because you're removing them from the list with each choice, and the choices are random because you shuffled the list before selecting any cards.