Skip to content

Instantly share code, notes, and snippets.

@righ
Created June 8, 2019 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/6c7d4e37433549f5d2fe3e13a65b0665 to your computer and use it in GitHub Desktop.
Save righ/6c7d4e37433549f5d2fe3e13a65b0665 to your computer and use it in GitHub Desktop.
It returns list sorted in zigzag.
def zigzag_sorted(iterable, key=None):
"""It returns list sorted in zigzag.
:rtype: generator object (iterator)
>>> list(zigzag_sorted([1, 2, 3, 4, 5, 6, 7]))
[1, 7, 2, 6, 3, 5, 4]
"""
i = 0
l = sorted(iterable, key=key)
n = len(l)
if not n:
return
for j in range(n):
yield l[i]
if j % 2 == 0:
i = -i - 1
else:
i = abs(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment