<jupyter_start><jupyter_text>A Pythonic Card Deck<jupyter_code>import collections

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

class FrenckDeck:
    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]
beer_card = Card("7", "diamonds")
print(beer_card)
dect = FrenckDeck()
len(dect)<jupyter_output><empty_output><jupyter_text>by using special methods, magics happen+ using common function such as len+ benefit from standard library<jupyter_code>from random import choice
choice(dect)<jupyter_output><empty_output><jupyter_text>by implementing the __getitem__, we can do:+ slicing+ iteration+ reverse iteration+ check contains<jupyter_code>dect[:4]
dect[12::13]
for card in dect[4::13]:
    print(card)
for card in reversed(dect[2::13]):
    print(card)
Card('7', 'hearts') in dect<jupyter_output><empty_output><jupyter_text>sorting<jupyter_code>suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def spades_high(card):
    rank_value = FrenckDeck.ranks.index(card.rank)
    return rank_value * len(suit_values) + suit_values[card.suit]
for card in sorted(dect[::6], key=spades_high):
    print(card)<jupyter_output>Card(rank='2', suit='spades')
Card(rank='5', suit='hearts')
Card(rank='6', suit='clubs')
Card(rank='7', suit='diamonds')
Card(rank='8', suit='spades')
Card(rank='J', suit='hearts')
Card(rank='Q', suit='clubs')
Card(rank='K', suit='diamonds')
Card(rank='A', suit='spades')
{'fraction_non_alphanumeric': 0.15221137277426766, 'fraction_numerical': 0.014933946008041356, 'mean_word_length': 5.623574144486692, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '337035', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 641, 'n_tokens_neox': 623, 'n_words': 134, 'path': 'books/FluentPython/fluent1.ipynb', 'repo_name': 'Bingwen-Hu/hackaway', 'size': '1741'}