Skip to content

Instantly share code, notes, and snippets.

@RandomEtc
Created November 11, 2012 06:45
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 RandomEtc/4053983 to your computer and use it in GitHub Desktop.
Save RandomEtc/4053983 to your computer and use it in GitHub Desktop.
def ftrain(list):
out = [ list[0] ]
stack = [ out ]
for i in list[1:]:
last = stack[-1][-1]
if i > last:
# start a new list
new = []
stack[-1].append(new)
stack.append(new)
while i < last:
# otherwise go back
stack.pop()
last = stack[-1][0]
# add to the end...
stack[-1].append(i)
return out
a = [ 1, 2, 3, 3, 4, 4, 2, 1 ]
b = ftrain(a)
print b
# should be = [ 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