06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

166 Sets of objects<br />

class Deck:<br />

...<br />

def shuffle(self):<br />

import random<br />

nCards = len(self.cards)<br />

for i in range(nCards):<br />

j = random.randrange(i, nCards)<br />

self.cards[i], self.cards[j] = self.cards[j], self.cards[i]<br />

Rather than assume that there are fifty-two cards in the deck, we get the actual<br />

length of the list and s<strong>to</strong>re it in nCards.<br />

For each card in the deck, we choose a random card from among the cards that<br />

haven’t been shuffled yet. Then we swap the current card (i) <strong>with</strong> the selected<br />

card (j). To swap the cards we use a tuple assignment, as in Section 9.2:<br />

self.cards[i], self.cards[j] = self.cards[j], self.cards[i]<br />

As an exercise, rewrite this line of code <strong>with</strong>out using a sequence assignment.<br />

15.8 Removing and dealing cards<br />

Another method that would be useful for the Deck class is removeCard, which<br />

takes a card as an argument, removes it, and returns True if the card was in the<br />

deck and False otherwise:<br />

class Deck:<br />

...<br />

def removeCard(self, card):<br />

if card in self.cards:<br />

self.cards.remove(card)<br />

return True<br />

else:<br />

return False<br />

The in opera<strong>to</strong>r returns true if the first operand is in the second, which must be<br />

a list or a tuple. If the first operand is an object, <strong>Python</strong> uses the object’s cmp<br />

method <strong>to</strong> determine equality <strong>with</strong> items in the list. Since the cmp in the Card<br />

class checks for deep equality, the removeCard method checks for deep equality.<br />

To deal cards, we want <strong>to</strong> remove and return the <strong>to</strong>p card. The list method pop<br />

provides a convenient way <strong>to</strong> do that:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!