Python Forum
how do i pass duplicates in my range iterator?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how do i pass duplicates in my range iterator?
#1
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))
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I'm really a novice at python; I'm actually a C# programmer can you show me how?
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to pass encrypted pass to pyodbc script tester_V 0 845 Jul-27-2023, 12:40 AM
Last Post: tester_V
  prime numbers with iterator and generator cametan_001 8 1,849 Dec-17-2022, 02:41 PM
Last Post: cametan_001
  remove partial duplicates from csv ledgreve 0 781 Dec-12-2022, 04:21 PM
Last Post: ledgreve
  resetting an iterator to full Skaperen 7 6,930 Feb-20-2022, 11:11 PM
Last Post: Skaperen
  Problem : Count the number of Duplicates NeedHelpPython 3 4,352 Dec-16-2021, 06:53 AM
Last Post: Gribouillis
  matplotlib x axis range goes over the set range Pedroski55 5 3,163 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  popping an iterator Skaperen 11 3,681 Oct-03-2021, 05:08 PM
Last Post: Skaperen
  q re glob.iglob iterator and close jimr 2 2,220 Aug-23-2021, 10:14 PM
Last Post: perfringo
  Problem with an iterator grimm1111 9 4,273 Feb-06-2021, 09:22 PM
Last Post: grimm1111
  Removal of duplicates teebee891 1 1,783 Feb-01-2021, 12:06 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020