In: Computer Science
push(self, value: object) -> None:
This method adds a new element to the top of the stack.
Output:
STACK: 0 elements. []
STACK: 5 elements. [1, 2, 3, 4, 5]
pop(self) -> object:
Output:
Exception: <class ' main .StackException'> 5
4
3
2
1
Exception: <class ' main .StackException'
top(self) -> object:
Output:
No elements in stack <class ' main .StackException'> STACK: 2 elements. [10, 20]
20
20
STACK: 2 elements. [10, 20]
#Code
from dynamic_array import *
class StackException(Exception):
"""
Custom exception to be used by Stack class
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
pass
class Stack:
def __init__(self):
"""
Init new stack based on Dynamic Array
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.da = DynamicArray()
def __str__(self) -> str:
"""
Return content of stack in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = "STACK: " + str(self.da.length()) + " elements. ["
out += ', '.join([str(self.da.get_at_index(_))
for _ in range(self.da.length())])
return out + ']'
def is_empty(self) -> bool:
"""
Return True is the stack is empty, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.is_empty()
def size(self) -> int:
"""
Return number of elements currently in the stack
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.length()
def push(self, value: object) -> None:
"""
TODO: Write this implementation
"""
pass
def pop(self) -> object:
"""
TODO: Write this implementation
"""
pass
def top(self) -> object:
"""
TODO: Write this implementation
"""
pass
# BASIC TESTING
if __name__ == "__main__":
print("\n# push example 1")
s = Stack()
print(s)
for value in [1, 2, 3, 4, 5]:
s.push(value)
print(s)
print("\n# pop example 1")
s = Stack()
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))
for value in [1, 2, 3, 4, 5]:
s.push(value)
for i in range(6):
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))
print("\n# top example 1")
s = Stack()
try:
s.top()
except Exception as e:
print("No elements in stack", type(e))
s.push(10)
s.push(20)
print(s)
print(s.top())
print(s.top())
print(s)
dynamic_array.py
import ctypes
class DynamicArray(object):
def __init__(self):
self.n = 0 # Count actual elements (Default is 0)
self.capacity = 1 # Default Capacity
self.A = self.make_array(self.capacity)
def length(self):
return self.n
def get_at_index(self, k):
if not 0 <= k <self.n:
return IndexError('Index out of bounds !')
return self.A[k] # Retrieve from the array at index k
def append(self, ele):
if self.n == self.capacity:
self._resize(2 * self.capacity)
self.A[self.n] = ele
self.n += 1
def pop(self):
if self.n==0:
print("Empty array")
return
else:
item = self.get_at_index(self.n-1)
self.n = self.n - 1
return item
def _resize(self, new_cap):
B = self.make_array(new_cap)
for k in range(self.n):
B[k] = self.A[k]
self.A = B
self.capacity = new_cap
def make_array(self, new_cap):
return (new_cap * ctypes.py_object)()
def top(self):
return self.get_at_index(self.n-1)
stack.py
from dynamic_array import *
class StackException(Exception):
"""
Custom exception to be used by Stack class
DO
"""
pass
class Stack:
da=DynamicArray()
def __init_(self):
"""
Init new stack based on Dynamic Array
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.da = DynamicArray()
def __str__(self) -> str:
"""
Return content of stack in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = "STACK: " + str(self.da.length()) + " elements. ["
out += ', '.join([str(self.da.get_at_index(_))
for _ in range(self.da.length())])
return out + ']'
def is_empty(self) -> bool:
"""
Return True is the stack is empty, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.is_empty()
def size(self) -> int:
"""
Return number of elements currently in the stack
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.length()
def push(self, value: object) -> None:
"""
TODO: Write this implementation
"""
self.da.append(value)
def pop(self) -> object:
"""
TODO: Write this implementation
"""
x = self.da.pop()
return x
def top(self) -> object:
"""
TODO: Write this implementation
"""
x = self.da.top()
return x
# BASIC TESTING
if __name__ == "__main__":
print("\n# push example 1")
s = Stack()
print(s)
for value in [1, 2, 3, 4, 5]:
s.push(value)
print(s)
print("\n# pop example 1")
s = Stack()
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))
for value in [1, 2, 3, 4, 5]:
s.push(value)
for i in range(6):
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))
print("\n# top example 1")
s = Stack()
try:
s.top()
except Exception as e:
print("No elements in stack", type(e))
s.push(10)
s.push(20)
print(s)
print(s.top())
print(s.top())
print(s)
Output