forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatten.py
78 lines (66 loc) · 2.44 KB
/
flatten.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Implement Flatten Arrays.
Given an array that may contain nested arrays,
produce a single resultant array.
"""
from collections import Iterable
# return list
def flatten(inputArr, outputArr=None):
if outputArr is None:
outputArr = []
for ele in inputArr:
if isinstance(ele, Iterable):
flatten(ele, outputArr)
else:
outputArr.append(ele)
return outputArr
# returns iterator
def flatten_iter(iterable):
"""
Takes as input multi dimensional iterable and
returns generator which produces one dimensional output.
"""
for element in iterable:
if isinstance(element, Iterable):
yield from flatten(element)
else:
yield element
import unittest
class TestFlatten(unittest.TestCase):
def test_flatten(self):
nested_list = [2, 1, [3, [4, 5], 6], 7, [8]]
flattened = flatten(nested_list)
self.assertEqual(flattened, [2, 1, 3, 4, 5, 6, 7, 8])
nested_list = [[3, [4, 5], 6], 7, [8]]
flattened = flatten(nested_list)
self.assertEqual(flattened, [3, 4, 5, 6, 7, 8])
nested_list = [[], [8]]
flattened = flatten(nested_list)
self.assertEqual(flattened, [8])
def test_flatten_iter(self):
nested_list = [2, 1, [3, [4, 5], 6], 7, [8]]
flattened = flatten_iter(nested_list)
self.assertEqual(next(flattened), 2)
self.assertEqual(next(flattened), 1)
self.assertEqual(next(flattened), 3)
self.assertEqual(next(flattened), 4)
self.assertEqual(next(flattened), 5)
self.assertEqual(next(flattened), 6)
self.assertEqual(next(flattened), 7)
self.assertEqual(next(flattened), 8)
self.assertRaises(StopIteration, next, flattened)
nested_list = [[3, [4, 5], 6], 7, [8]]
flattened = flatten_iter(nested_list)
self.assertEqual(next(flattened), 3)
self.assertEqual(next(flattened), 4)
self.assertEqual(next(flattened), 5)
self.assertEqual(next(flattened), 6)
self.assertEqual(next(flattened), 7)
self.assertEqual(next(flattened), 8)
self.assertRaises(StopIteration, next, flattened)
nested_list = [[], [8]]
flattened = flatten_iter(nested_list)
self.assertEqual(next(flattened), 8)
self.assertRaises(StopIteration, next, flattened)
if __name__ == "__main__":
unittest.main()