-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathstack_using_array.py
More file actions
40 lines (31 loc) · 1.1 KB
/
stack_using_array.py
File metadata and controls
40 lines (31 loc) · 1.1 KB
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
class Stack:
def __init__(self, initial_size = 10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0
self.num_elements = 0
def push(self, data):
if self.next_index == len(self.arr):
print("Out of space! Increasing array capacity ...")
self._handle_stack_capacity_full()
self.arr[self.next_index] = data
self.next_index += 1
self.num_elements += 1
def pop(self):
if self.is_empty():
self.next_index = 0
return None
self.next_index -= 1
self.num_elements -= 1
return self.arr[self.next_index]
def size(self):
return self.num_elements
def is_empty(self):
return self.num_elements == 0
def _handle_stack_capacity_full(self):
old_arr = self.arr
self.arr = [0 for _ in range( 2* len(old_arr))]
for index, element in enumerate(old_arr):
self.arr[index] = element
foo = Stack()
print(foo.arr)
print("Pass" if foo.arr == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] else "Fail")