Last active
December 21, 2015 06:23
-
-
Save k5trismegistus/868b3e34274e389f2913 to your computer and use it in GitHub Desktop.
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
test = [1, 2, 3, [4, 5], 6, 7, [8, [9, 10]], [[11, 12, [13, 14]]]] | |
def greedy_flatten(seq): | |
if not isinstance(seq, list): | |
return seq | |
seq = seq.copy() | |
while any([isinstance(x, list) for x in seq]): | |
for idx, x in enumerate(seq): | |
if isinstance(seq[idx], list): | |
tmp = seq.pop(idx) | |
flatten_tmp = greedy_flatten(tmp) | |
for sub_idx, sub_x in enumerate(flatten_tmp): | |
seq.insert(idx+sub_idx, sub_x) | |
return seq | |
def test_greedy_flatten(): | |
test = [1, 2, 3, [4, 5], 6, 7, [8, [9, 10]], [[11, 12, [13, 14]]]] | |
assert greedy_flatten(test) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] | |
assert test == [1, 2, 3, [4, 5], 6, 7, [8, [9, 10]], [[11, 12, [13, 14]]]] | |
print('pass') | |
test_greedy_flatten() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment