Cycle around a sequence

Terry Reedy tjreedy at udel.edu
Wed Feb 8 21:15:59 CET 2012


On 2/8/2012 9:25 AM, Neil Cerutti wrote:
> On 2012-02-08, Mark Lawrence<breamoreboy at yahoo.co.uk>  wrote:
>> I'm looking at a way of cycling around a sequence i.e. starting
>> at some given location in the middle of a sequence and running
>> to the end before coming back to the beginning and running to
>> the start place.  About the best I could come up with is the
>> following, any better ideas for some definition of better?
>
> Python's indices were designed for these kinds of shenanigans.
>
> def rotated(seq, n):
>      """Iterate through all of seq, but starting from index n.
>
>      >>>  ", ".join(str(n) for n in rotated(range(5), 3))
>      '3, 4, 0, 1, 2'
>      """
>
>      i = n - len(seq)
>      while i<  n:
>          yield seq[i]
>          i += 1

This is really nice, in the category of "Why didn't I think of that?"
(Probably because I knew the % mod solution from C and never 'updated'!)

> if __name__ == "__main__":
>      import doctest
>      doctest.testmod()
>
> If you have merely an iterable instead of a sequence, then look
> to some of the other clever stuff already posted.

To make a repeating rotator is only a slight adjustment:

     k = n - len(seq)
     while True:
         i = k
         while i < n:
             yield seq[i]
             i += 1

-- 
Terry Jan Reedy




More information about the Python-list mailing list