Python puzzle 1 solution
Following up on the Python puzzle I posted a couple of days ago, let's talk about a solution
First, thanks for everyone that sent a solution, even over DM!!
My grouping solution uses two concepts:
- Iterator
- zip with * operator
Why does it work and what's the advantage?
The iterator object gives you an API to traverse a collection
When we use "iters = [iter(inputs)] * n" we are creating a list of "n" copies of the same iterator.
To make sure, you can just print iters and see that they are all references to the same iterator.
Now the zip with * operator will unpack the list of iterator:
iters = [iter1, iter2, iter3]
zip(*iters) -> zip(iter1, iter2, iter3)
Why does it work?
zip will iterate over the same iterator repeated n times
When zip get's the first elements for all inputs, it's just like iterating over the first n elements of "nums"
nums = [1, 2, 3, 4] iters = [iter(nums)] *2
zip(*iters) -> zip([1, 3], [2, 4])
The other advantage of this solution is that the output wasn't really evaluated until you cast it as a list or request some item.
This is very good memory wise.
The last part is if the size of numbers is not a multiple of n (as pointed out in some solutions).
For this we can evolve our solution to use the itertools library. It provides the zip_longest function that is just like zip but will pad with a fillvalue the remaining items
Hope this was useful and you can apply this knowledge on your future code!