Exploring permutations() and product()
00:00 In this lesson, you’ll meet two more brute-force tools: permutations(), which rearranges items, and product(), which replaces nested for loops. You’ll use product() to build a deck of cards.
00:13 permutations() yields every possible ordering of its input. Three letters have six orderings, from abc all the way to cba. But ten items already have more than three and a half million orderings.
00:28 An iterable with n elements has n factorial permutations. Two items have two orderings, and three items have six. By five items, you’re at a hundred and twenty.
00:38 By eight, it’s over forty thousand. And by ten, you’re past three and a half million. This is called a combinatorial explosion, where just a few inputs produce a huge number of outcomes.
00:50 Every brute-force function in itertools can cause one. Now say you’re building a poker app. A card is a tuple of a rank and a suit, and you want a deck that hands out cards one at a time.
01:02 A generator with a nested for loop does the job. Mathematically, this nested loop is a Cartesian product. It pairs every rank with every suit. Here’s what a Cartesian product looks like.
01:14 Take three ranks, ace, king, and queen, and four suits, hearts, diamonds, clubs, and spades. The product pairs each rank with each suit, row by row, exactly like the nested loop.
01:25 Three ranks times four suits gives you twelve cards. With all thirteen ranks, you get the full deck of fifty-two. itertools has a function for exactly this, called product().
01:37 It takes any number of iterables and yields every tuple in their Cartesian product. Splitting a string is a short way to build the same list of thirteen ranks.
01:49 Then add the four suits.
01:52 Now one call to product() replaces the whole nested loop, and it’s still lazy. The first card is the ace of hearts, followed by the ace of diamonds.
02:04 In this lesson, you rearranged items with permutations(), saw how fast n factorial grows, and built a deck of cards with product(). Brute force is usually something to avoid, but sometimes every possible outcome matters, and then itertools has you covered.
02:21 You’ll come back to the deck later. Next up, though, you’ll explore iterators that never end.
Become a Member to join the conversation.