Python Forum
Cute oscillating range generation snippet I saw on irc
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cute oscillating range generation snippet I saw on irc
#1
Iterating both up and down from the middle of a range, with only the range max value input:

import itertools
def spiral(n):
    r1 = range(n // 2, n)
    r2 = range(n // 2 - 1, -1, -1)
    for a, b in itertools.zip_longest(r1, r2):
        yield a
        if b is not None:
            yield b
   
And some application:

list(spiral(6))
[3, 2, 4, 1, 5, 0]
Reply
#2
In python 3, range() has a lot of extra features that weren't available in 2.x, such as indexing and slicing. It's fast, even on large ranges, as it computes the values when indexed, instead of iterating over the range.

So another, probably worse, way of doing it, could be like so:
>>> def spiral(size):
...   spinner = range(size)
...   right = len(spinner) // 2
...   left = right - 1
...   exhaused = False
...   while not exhaused:
...     exhaused = True
...     if right < len(spinner):
...       yield spinner[right]
...       right += 1
...       exhaused = False
...     if left >= 0:
...       yield spinner[left]
...       left -= 1
...       exhaused = False
...
>>> list(spiral(6))
[3, 2, 4, 1, 5, 0]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Advanced CLI Snippet Manager bytebutcher 1 2,560 Sep-20-2020, 11:58 AM
Last Post: bytebutcher
  Checkbox snippet menator01 0 2,332 May-16-2020, 08:26 AM
Last Post: menator01
  Module for procedural generation with hashes PhilHibbs 8 5,240 Feb-28-2018, 02:07 PM
Last Post: PhilHibbs
  snippet: dp and pv Skaperen 0 2,896 Apr-08-2017, 07:17 AM
Last Post: Skaperen
  Password Snippet Kai. 9 8,085 Nov-10-2016, 08:11 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020