-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflattenArray.py
More file actions
38 lines (32 loc) · 959 Bytes
/
flattenArray.py
File metadata and controls
38 lines (32 loc) · 959 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
31
32
33
34
35
36
37
38
__author__ = 'kathan'
def flattenArrayIterative(array):
i = len(array)
result = []
index = 0
while i > 0:
if isinstance(array[index], list):
i += len(array[index]) - 1
temp_index = index
temp_array = array[index]
del array[index]
for j in range(len(temp_array)):
array.insert(temp_index, temp_array[j])
temp_index += temp_index
else:
result.append(array[index])
i -= 1
index += 1
return result
def flattenArrayRecursively(array):
length = len(array)
res = []
for i in range(length):
if isinstance(array[i], list):
res = res + flattenArrayRecursively(array[i])
else:
res.append(array[i])
return res
if __name__ == '__main__':
a = [1, [2, [3, [4, [5, [6]]]]]]
print flattenArrayIterative(a)
print flattenArrayRecursively(a)