Python Forum
"Card Dealing" Python code 2.7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"Card Dealing" Python code 2.7
#4
I Wasn't too sure if I should add two cents or not.
This is for illustration purposes of other ways to create a deck:

Fluent Python is one of my favorite python books:

# attribution:
# “Fluent Python by Luciano Ramalho (O’Reilly).
#  Copyright 2015 Luciano Ramalho, 978-1-491-94600-8.
import collections
from random import shuffle

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


class FrenchDeck(collections.MutableSequence):
    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]

    def __setitem__(self, position, value):  # <1>
        self._cards[position] = value

    def __delitem__(self, position):  # <2>
        del self._cards[position]

    def insert(self, position, value):  # <3>
        self._cards.insert(position, value)


def main():
    deck = FrenchDeck()
    shuffle(deck)
    for card in deck:
        print(card)


if __name__ == '__main__':
    main()
Reply


Messages In This Thread
"Card Dealing" Python code 2.7 - by Paradoxalis - Nov-17-2016, 09:48 PM
RE: "Card Dealing" Python code 2.7 - by micseydel - Nov-17-2016, 11:18 PM
RE: "Card Dealing" Python code 2.7 - by metulburr - Nov-17-2016, 11:28 PM
RE: "Card Dealing" Python code 2.7 - by Larz60+ - Nov-17-2016, 11:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel from SAP - dealing with formats and VBA MasterOfDestr 7 590 Feb-25-2024, 12:23 PM
Last Post: Pedroski55
  UnicodeEncodeError - Dealing with Japanese Characters fioranosnake 2 2,495 Jul-07-2022, 08:43 PM
Last Post: fioranosnake
  Having strange results from an RFID HID card reader - I'm stuck orbisnz 1 1,501 Mar-28-2022, 08:20 AM
Last Post: Larz60+
  SQL wild card use hammer 3 1,283 Jan-07-2022, 02:17 PM
Last Post: hammer
  Dealing with duplicated data in a CSV file bts001 10 11,577 Sep-06-2021, 12:11 AM
Last Post: SamHobbs
  Dealing with a .json nightmare... ideas? t4keheart 10 4,415 Jan-28-2020, 10:12 PM
Last Post: t4keheart
  Dealing with Exponential data parthi1705 11 9,820 May-30-2019, 10:16 AM
Last Post: buran
  Credit card number redacting script Drone4four 6 5,220 Jan-18-2019, 02:07 PM
Last Post: Drone4four
  Dealing with multiple context managers heras 5 4,727 Nov-16-2018, 09:01 AM
Last Post: DeaD_EyE
  Validating credit card frequency 8 4,208 Nov-05-2018, 07:36 PM
Last Post: frequency

Forum Jump:

User Panel Messages

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