Create a class `Deck` that represents a standard deck of 52 playing cards. Each card is represented as a string with rank followed by suit, e.g., `"AS"` for Ace of Spades, `"10H"` for Ten of Hearts. The deck should be initialized in the following order: for each suit in order `S` (Spades), `H` (Hearts), `D` (Diamonds), `C` (Clubs), include all ranks in order `"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"`. So the initial deck starts with `["AS", "2S", "3S", ..., "KS", "AH", ...]`.
Implement the following methods:
- `__init__(self)`: initializes the deck as described. The cards must be stored in an attribute named `cards` (a list).
- `shuffle(self)`: randomly shuffles the deck in place using the `random` module (e.g., `random.shuffle`).
- `deal(self)`: removes and returns the top card (the first card in the list). If the deck is empty, raise `IndexError` with message `"No cards left"`.
- `__len__(self)`: returns the number of cards remaining in the deck.
Use the `random` module for shuffling. Ensure that `shuffle` modifies the deck order randomly.
Constraints
The deck always starts with 52 unique cards. Methods must work for an empty deck after all cards have been dealt. No external packages beyond the standard library.
Example
>>> d = Deck()
>>> len(d)
52
>>> card = d.deal()
>>> card
'AS'
>>> len(d)
51
>>> d.shuffle()
>>> len(d)
51
>>> d2 = Deck()
>>> d2.shuffle()
>>> d2.deal() in [r+s for r in ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] for s in 'SHDC']
True
10 points
~15 min
Recent Submissions
No submissions yet — hit Run Tests to try!
Hints
In __init__, build the list using nested loops over suits and ranks, and assign to self.cards.
Use random.shuffle(self.cards) inside shuffle.
In deal, check if the deck is empty and raise IndexError, otherwise use pop(0) to remove the first card.
__len__ should return len(self.cards).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.