-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastarraystack.py
53 lines (40 loc) · 1.31 KB
/
fastarraystack.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
'''
An array-based list implementation with O(1+n-i) amortized update time.
Stores the list in an array, a, so that the i'th list item is stored
at a[(j+i)%len(a)].
Uses a doubling strategy for resizing a when it becomes full or too empty.
'''
from utils import new_array
from base import BaseList
class FastArrayStack(BaseList):
def __init__(self, iterable=[]):
self._initialize()
self.add_all(iterable)
def _initialize(self):
self.a = new_array(1)
self.n = 0
def get(self, i):
if i < 0 or i >= self.n: raise IndexError()
return self.a[i]
def set(self, i, x):
if i < 0 or i >= self.n: raise IndexError()
y = self.a[i]
self.a[i] = x
return y
def add(self, i, x):
if i < 0 or i > self.n: raise IndexError()
if self.n == len(self.a): self._resize()
self.a[i+1:self.n+1] = self.a[i:self.n]
self.a[i] = x
self.n += 1
def remove(self, i):
if i < 0 or i >= self.n: raise IndexError()
x = self.a[i]
self.a[i:self.n-1] = self.a[i+1:self.n]
self.n -= 1
if len(self.a) >= 3*self.n: self._resize()
return x
def _resize(self):
b = new_array(max(1, 2*self.n))
b[0:self.n] = self.a[0:self.n]
self.a = b