Skip to content

Instantly share code, notes, and snippets.

@keroserene
Created November 11, 2012 08:06
Show Gist options
  • Save keroserene/4054130 to your computer and use it in GitHub Desktop.
Save keroserene/4054130 to your computer and use it in GitHub Desktop.
Reorganize basic list into nested lists, with similar elements per level.
# 2012.11.11 - 02:44:45
# (Python 3.3)
def nest(bird):
"""Recursively nest similar elements at same level."""
if not bird: return []
beak = bird[0] # Current element to match for this level.
egg = []
prev = 0
while beak in bird:
next = bird.index(beak)
# Jump to relevant index and update context.
if next > prev:
egg += [nest(bird[prev:next])]
egg += [bird[next]]
bird = bird[next+1:]
# Trailing non-similars.
if prev < len(bird): egg += [bird[prev:]]
return egg
test = [1,2,3,3,4,4,2,1]
print(nest(test)) # [1, [2, [3, 3, [4, 4]], 2], 1]
@keroserene
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment