Python - Why Python?: Similar but Different - set, remove method
Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly Guide、 Paul Barry(著)、 O’Reilly Mediaの Chapter1.(Why Python?: Similar but Different)、EXERCISE(55/95)の解答を求めてみる。
Jupyter(コード、入出力結果)
Cards.ipynb
def draw():
card = random.choice(list(deck))
deck.remove(card)
return card
draw()
(5, 'of', 'Diamonds')
len(deck)
51
draw()
('King', 'of', 'Hearts')
len(deck)
50
for _ in range(51):
draw()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[21], line 2
1 for _ in range(51):
----> 2 draw()
Cell In[15], line 2, in draw()
1 def draw():
----> 2 card = random.choice(list(deck))
3 deck.remove(card)
4 return card
File /opt/local/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/random.py:351, in Random.choice(self, seq)
348 # As an accommodation for NumPy, we don't use "if not seq"
349 # because bool(numpy.array()) raises a ValueError.
350 if not len(seq):
--> 351 raise IndexError('Cannot choose from an empty sequence')
352 return seq[self._randbelow(len(seq))]
IndexError: Cannot choose from an empty sequence