[Python-ideas] Rewriting the "roundrobin" recipe in the itertools documentation

Terry Reedy tjreedy at udel.edu
Mon Nov 20 19:56:09 EST 2017

```On 11/16/2017 5:57 PM, Terry Reedy wrote:
> On 11/16/2017 2:56 PM, Terry Reedy wrote:
>
> Correct off-by-one error.  I should have tested with an edge case such as
> print(list(roundrobin('ABC', '')))
>
>> The following combines 3 statements into one for statement.
>>
>> def roundrobin(*iterables):
>>      "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
>>      nexts = cycle(iter(it).__next__ for it in iterables)
>>      for reduced_len in reversed(range(1, len(iterables))):
>
> Make that 0 rather than 1 for start value.
>
>>          try:
>>              for next in nexts:
>>                  yield next()
>>          except StopIteration:
>>              nexts = cycle(islice(nexts, reduced_len))
>
> A slightly clearer, slightly less efficient alternative would be
>
> def roundrobin(*iterables):
>      "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
>      nexts = cycle(iter(it).__next__ for it in iterables)
>      for current_len in reversed(range(1, len(iterables)+1)):
>          try:
>              for next in nexts:
>                  yield next()
>          except StopIteration:
>              nexts = cycle(islice(nexts, current_len - 1))

I submitted the 'current_len' version as
https://bugs.python.org/issue32099
"Use range in itertools roundrobin recipe"

--
Terry Jan Reedy

```