Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Shuffling and Cutting the Deck
00:00 In this lesson, you’ll shuffle your deck of cards, and then cut it with three new tools, tee(), islice(), and chain(), without making a copy of the deck.
00:10 Any poker app worth its salt starts with a shuffled deck. The random module has a shuffle() function, but it only works on a list, so your shuffle() function copies the deck into a list first, shuffles it in place, and hands back a fresh iterator.
00:26 There’s no good way to shuffle an iterator without a copy. Set a seed, so that your shuffle matches the one in this course. Then build a new deck with product() and shuffle it.
00:40 Next, your players should be able to cut the deck. They pick a number n, and you move the top n cards to the bottom. With list slicing, the top is deck up to n and the bottom is deck from n onward, so you put the bottom first.
00:55 But slicing copies the list. With fifty-two cards, that hardly matters, but you can avoid the copy with three tools from itertools. The first tool is tee().
01:06 It splits one iterable into several independent iterators. Ask tee() for two iterators over five numbers. The first one yields all five numbers, and then it’s exhausted.
01:22 The second iterator still yields all five. It works independently of the first. To do that, tee() gives each iterator its own queue. When the first iterator pulls a value from the source, tee() copies that value into the second iterator’s queue.
01:38 If the first iterator runs all the way to the end before the second one starts, then the second queue ends up holding a copy of everything. So use tee() with care, and only when your iterators stay close together.
01:52 The second tool is islice(). It slices any iterable and returns an iterator. Slicing from two to five gives you C, D, and E, just like slicing a list. A stop of None means you go all the way to the end.
02:09 With a single number, islice() takes the first few items. The third tool is chain(), which links iterables together, one after the other. Put the three tools together, and you can cut a deck without slicing a list.
02:23 tee() gives you two iterators over the deck. islice() takes the top n cards from one, and everything after them from the other. Then chain() puts the bottom first.
02:32 Since islice() rejects negative numbers, you don’t need your own check anymore. Cut ten numbers at three, and the first three move to the end. Now cut your shuffled deck in half.
02:45 In this lesson, you shuffled your deck and then cut it with tee(), islice(), and chain(). Of these, tee() is the one to watch, because it can quietly store a whole iterable in memory.
02:57 Next up, you’ll deal some hands and flatten a list of lists.
Become a Member to join the conversation.