Created
November 11, 2012 08:06
-
-
Save keroserene/4054130 to your computer and use it in GitHub Desktop.
Reorganize basic list into nested lists, with similar elements per level.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Re: https://twitter.com/ftrain/status/267503513477713920