Problem overview
You write two classes. A Card has a rank and a suit, and its label() joins them, as in "10H". A Deck holds 52 cards and supports cut(k), perfect_shuffle(), deal(count) and remaining(). The lesson's tests make one deck, call the methods in order and print each deal as labels separated by spaces (or none for an empty hand) and each remaining as a number.
A new deck is ordered by suit, then rank: the clubs AC 2C ... KC, then diamonds, hearts and spades, so AC is on top and KS at the bottom. Nothing is random.
cut(k)moves the topkcards to the bottom, keeping their order.perfect_shuffle()splits the deck into a top half and a bottom half, then takes one card from each half in turn, top half first. With an odd count the top half gets the extra card:1 2 3 4 5becomes1 4 2 5 3.deal(count)removescountcards from the top and returns them, top card first, or all that are left if there are fewer.
For example, a new deck dealt three cards gives AC 2C 3C and leaves 49. After perfect_shuffle() on a new deck, the first four cards are AC AH 2C 2H: the top half is the clubs and diamonds, the bottom half the hearts and spades, and the shuffle alternates between them.
Approach: a queue for the cards, a list for the shuffle
The deck is a sequence where cards leave from the top and, after a cut, return at the bottom. Python's collections.deque is built for that: popleft() removes from the front and append() adds at the back, both in O(1). A plain list would make pop(0) shift every other card, which costs O(n) each time. So the front of the deque is the top of the deck.
A cut is then a loop that runs k times, each time moving the front card to the back. One card at a time keeps the moved cards in their order, and the cut costs O(k).
The shuffle needs to read card i of each half, and a deque is slow at reading the middle. So the shuffle copies the cards into a list order, where any position is O(1), and builds the deck again from it. The top half has (len(order) + 1) // 2 cards: the + 1 hands the extra card of an odd count to the top half (5 cards give 3 and 2; 52 give 26 and 26). In round i, the card order[i] from the top half goes in, then order[half + i] from the bottom half, if one exists.
Dealing must not loop count times, since count can be a billion. The loop instead stops when the hand is full or the deck is empty, so it runs at most 52 times.
Step by step
- Store rank and suit in the
Cardconstructor, as public fields: the program reads every card's data. - Return rank plus suit from
label. Adding two strings joins them. - Create an empty
dequeinDeck.__init__, as the private field_cards. - Write the suits and ranks in order as two lists.
- Use two nested loops, suits outside and ranks inside, appending a new
Card(rank, suit)each time. This makes 4 × 13 = 52 cards with the clubs first. - Cut: repeat
ktimes, popping the front card and appending it at the back. - Shuffle: copy the cards to a list, reset the deque to empty, compute the size of the top half, and loop over
range(half). - In each shuffle round, append the top-half card, then append the bottom-half card only if its position is still inside the list.
- Deal: collect cards into a list while it is shorter than
countand the deck isn't empty, then return the list. - Remaining: return the length of the deque.
The solution in Python
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def label(self):
return self.rank + self.suit
class Deck:
def __init__(self):
self._cards = deque()
suits = ["C", "D", "H", "S"]
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
for suit in suits:
for rank in ranks:
self._cards.append(Card(rank, suit))
def cut(self, k):
for _ in range(k):
self._cards.append(self._cards.popleft())
def perfect_shuffle(self):
order = list(self._cards)
self._cards = deque()
half = (len(order) + 1) // 2
for i in range(half):
self._cards.append(order[i])
if half + i < len(order):
self._cards.append(order[half + i])
def deal(self, count):
hand = []
while len(hand) < count and len(self._cards) > 0:
hand.append(self._cards.popleft())
return hand
def remaining(self):
return len(self._cards)
The solution uses deque from the collections module. In a file of your own, add from collections import deque at the top.
Notes on the code:
for _ in range(k)uses_for a loop variable the body doesn't need.self._cards.append(self._cards.popleft())works becausepopleft()returns the card it removes.- Both
len(self._cards)andlist(self._cards)work on a deque as on a list. - The shuffle assigns a new deque to
self._cardsinstead of clearing the old one. That is fine becauseorderalready holds the old cards. - A deal returns
Cardobjects, not strings. To print them, calllabel()on each one.
Using the classes:
deck = Deck()
print(" ".join(c.label() for c in deck.deal(3)), deck.remaining())
deck.cut(10)
print(" ".join(c.label() for c in deck.deal(2)), deck.remaining())
deck = Deck()
deck.perfect_shuffle()
print(" ".join(c.label() for c in deck.deal(4)), deck.remaining())
deck = Deck()
for _ in range(8):
deck.perfect_shuffle()
print(" ".join(c.label() for c in deck.deal(5)))
AC 2C 3C 49
AD 2D 47
AC AH 2C 2H 48
AC 2C 3C 4C 5C
The last line shows that eight perfect shuffles bring a 52-card deck back to its starting order. Dealing more than is left, such as deal(1000000000) on a deck with 2 cards, returns those 2 cards and leaves remaining() at 0.
Complexity
Building the deck is O(n) for n = 52 cards. cut(k) costs O(k), and since k is at most the number of cards, it is O(n). perfect_shuffle copies the cards and rebuilds the deck: O(n) time and O(n) extra space for the list. deal removes at most n cards, so it is O(n) even for a huge count, and remaining is O(1).
Edge cases and common mistakes
- Looping
counttimes indeal. With a count of a billion, that never finishes and fails once the deck is empty. Stop when the deck is empty. - Using a list with
pop(0). It works, but every removal shifts all the remaining cards. A deque is the right tool. - Half size with
len // 2. For an odd count the top half would be one card short, and the shuffle would lose the last card (5 cards would give1 3 2 4). Use(len + 1) // 2. - Reading past the end in the shuffle. With an odd count, the last round has no bottom card. The
if half + i < len(order)test skips it. - Shuffling in place while reading. Rebuilding from the same deque you are reading mixes up old and new positions. Copy first.
- Cutting by 0 or by the whole deck. Both leave the order unchanged, and the loop handles them with no special case.
- Dealing from an empty deck. The result is an empty list, which the tests print as
none.
