Rodrigo πŸπŸš€
Rodrigo πŸπŸš€

@mathsppblog

7 Tweets 2 reads Jul 25, 2024
Python combinatorial iterators from the module `itertools`...
Explained with ice cream 🍨🍦!
πŸ‘‡
The module `itertools` has 4 combinatorial iterators:
1. `combinations`
2. `combinations_with_replacement`
3. `permutations`
4. `product`
Their essence is that they combine the elements of the input iterable(s) in different ways.
`combinations(iterable, r)`
This iterator will produce tuples of length `r` with all the unique combinations of values from `iterable`.
β€œUnique” will make use of the original position in `iterable`, and not the value itself.
E.g., what ice cream flavour combinations can I get?
`combinations_with_replacement(iterable, r)`
Same as `combinations`, but values can be repeated.
E.g., what ice cream flavour combinations can I get if I allow myself to repeat flavours?
`permutations(iterable, r)`
All possible combinations of size `r` in all their possible orderings.
E.g., if I get 2 scoops, how can they be served?
This is a very important question because the flavour at the bottom is eaten last!
`product(*iterables, repeat=1)`
Matches up all values of all iterables together.
(Computes the cartesian product of the given iterables.)
E.g., if I can get either 2 or 3 scoops, and if the ice cream can be served on a cup or on a cone, how many different orders are there?
That's it!
These were the 4 combinatorial iterators from the module `itertools` explained with ice cream.
The module `itertools` has 20 tools that you should definitely learn about.
The article below goes over all of them with simple examples πŸ‘‡
mathspp.com

Loading suggestions...