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
#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


Messages In This Thread
RE: Cute oscillating range generation snippet I saw on irc - by nilamo - Mar-26-2018, 04:19 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Advanced CLI Snippet Manager bytebutcher 1 2,618 Sep-20-2020, 11:58 AM
Last Post: bytebutcher
  Checkbox snippet menator01 0 2,382 May-16-2020, 08:26 AM
Last Post: menator01
  Module for procedural generation with hashes PhilHibbs 8 5,358 Feb-28-2018, 02:07 PM
Last Post: PhilHibbs
  snippet: dp and pv Skaperen 0 2,946 Apr-08-2017, 07:17 AM
Last Post: Skaperen
  Password Snippet Kai. 9 8,238 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