forked from thundergolfer/interview-with-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatten-array.py
More file actions
30 lines (20 loc) · 737 Bytes
/
flatten-array.py
File metadata and controls
30 lines (20 loc) · 737 Bytes
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
30
"""accepts a multi dimensional array and returns a flattened version"""
def flatten_array(orig):
"""returns a new, flattened, list"""
flattened_list = []
for item in orig:
if isinstance(item, list):
flattened_list += flatten_array(item)
else:
flattened_list.append(item)
return flattened_list
def flatten_in_place(orig):
"""flattens a given list in place"""
is_flattened = False
while not is_flattened: # iterating until no more lists are found
is_flattened = True
for i, item in enumerate(orig):
if isinstance(item, list):
is_flattened = False
orig = orig[:i] + item + orig[i + 1:]
return orig