-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelasticlist.py
133 lines (113 loc) · 2.93 KB
/
elasticlist.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
"""
This is a datatype that simulates the behavior of the "infinite" list.
ElasticList data structure can be stretched and shrinked.
"""
class ElasticList(list):
"""ElasticList data structure.
The data structure inherits most methods from the default list.
NOTE: We define sparsity as the frequency of None values.
If frequency >= 50% then sparse else not.
"""
def __init__(self, items: list = []) -> None:
self._items = items
def __repr__(self):
return f"ElasticList({str(self._items)[1:-1]})"
def stretch(self, degree: int = 2) -> None:
"""Perform a uniform stretch of the list.
NOTE: This makes the list less sparse.
"""
stretcher = lambda x: [x] + [
None for i in range(len(self._items) * degree)
]
self._items = sum(list(map(stretcher, self._items)), [])
def shrink(self, filter: str = "even") -> None:
"""Perform a uniform shrink of the list.
Either leave even-indexed values or the odd-indexed values.
NOTE: This makes the list more sparse.
"""
if filter == "even":
self._items = [
self._items[i] for i in range(len(self._items)) if i % 2 == 0
]
else:
self._items = [
self._items[i] for i in range(len(self._items)) if i % 2 == 1
]
def main():
"""Testing ElasticList datatype"""
# Testing 'ElasticList' creation
try:
elastic_list = ElasticList([1, 2, 3])
print("Test 0 passed")
except:
print("Test 0 failed")
# Testing magic method '__repr__'
if repr(elastic_list) == "ElasticList(1, 2, 3)":
print("Test 1 passed")
else:
print("Test 1 failed")
# Testing method 'stretch'
elastic_list.stretch(3)
if elastic_list == ElasticList(
[
1,
None,
None,
None,
None,
None,
None,
None,
None,
None,
2,
None,
None,
None,
None,
None,
None,
None,
None,
None,
3,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
):
print("Test 2 passed")
else:
print("Test 2 failed")
# Testing method 'shrink'
elastic_list.shrink()
if elastic_list == ElasticList(
[
1,
None,
None,
None,
None,
2,
None,
None,
None,
None,
3,
None,
None,
None,
None,
]
):
print("Test 3 passed")
else:
print("Test 3 failed")
if __name__ == "__main__":
main()