Skip to content

Instantly share code, notes, and snippets.

@poundifdef
Created November 11, 2012 07:03
Show Gist options
  • Save poundifdef/4054037 to your computer and use it in GitHub Desktop.
Save poundifdef/4054037 to your computer and use it in GitHub Desktop.
def ftrain(l):
"""https://twitter.com/ftrain/status/267503513477713920
Assumes list will be "deepest" in the center
"""
# are all elements the same? group together and return
if len(set(l)) <= 1:
return l
# find 'start' of a group
for k, val in enumerate(l):
if val != l[0]:
start = k
break
# find 'end' of a group
for k, val in reversed(list(enumerate(l))):
if val != l[0]:
end = k + 1
break
out = l[:start]
out.append(ftrain(l[start:end]))
out.extend(l[end:])
return out
l = [1,2,3,3,4,4,2,1]
print ftrain(l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment