-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat_list.py
29 lines (24 loc) · 1.34 KB
/
flat_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
flat_list = lambda root_list: [element for sub_list in root_list for element in flat_list(sub_list)] \
if type(root_list) is list else [root_list]
if __name__ == '__main__':
assert flat_list([1, 2, 3]) == [1, 2, 3], "First"
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], "Second"
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], "Third"
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], "Four"
print('Done! Check it')
def flat_list(root_list):
if type(root_list) is list:
return [element for sub_list in root_list for element in flat_list(sub_list)]
else:
return [root_list]
if __name__ == '__main__':
assert flat_list([1, 2, 3]) == [1, 2, 3], "First"
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], "Second"
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], "Third"
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], "Four"
assert flat_list([[['a']], [1, ['b', 2, ['c'], 3, 'd', 4], 'e']]) == \
['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e'], 'different type of element'
print('All tests done and passed!')
'''
itertools.chain.from_iterable(root_list) will fail if an element of root_list is not an iterable ex: an integer
'''