Created
November 11, 2012 07:03
-
-
Save poundifdef/4054037 to your computer and use it in GitHub Desktop.
Function for: https://twitter.com/ftrain/status/267503513477713920
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
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