Skip to content

Instantly share code, notes, and snippets.

@davclark
Created November 11, 2012 21:04
Show Gist options
  • Save davclark/4056258 to your computer and use it in GitHub Desktop.
Save davclark/4056258 to your computer and use it in GitHub Desktop.
An apology to Paul
def ftrain(l):
'''Convert an iterable to a nested list based on ordered comparison'''
i = iter(l)
tree, seen = ftrain_helper(i, i.next())
# This might not be the desired behavior, but it's not terrible
# You could also emit a warning or an exception here
while(not seen is None):
rest_tree, seen = ftrain_helper(i, seen)
tree = [tree] + rest_tree
return tree
def ftrain_helper(i, curr_level):
'''Iterate, call down when reach a larger level, return when level drops'''
out = [curr_level]
while(True):
try:
next = i.next()
except StopIteration:
# This is the only place we actually return to the ftrain function
return out, None
if next > curr_level:
nested, seen = ftrain_helper(i, next)
out.append(nested)
if seen is None or seen < curr_level:
return out, seen
else:
out.append(seen)
elif next == curr_level:
out.append(next)
if next < curr_level:
return out, next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment