Skip to content

Instantly share code, notes, and snippets.

@k5trismegistus
Last active December 21, 2015 06:23
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 k5trismegistus/868b3e34274e389f2913 to your computer and use it in GitHub Desktop.
Save k5trismegistus/868b3e34274e389f2913 to your computer and use it in GitHub Desktop.
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