-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
55 lines (48 loc) · 1.58 KB
/
stack.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
from lists import Lists
class Stack(Lists):
def __init__(self, elements):
"""
Constructs all the necessary attributes for the stack object.
Parameters:
elements (str): A string wiht comma-separeted values to be converted in list.
"""
super().__init__(elements)
def push(self, element):
"""
Inserts an element at the top of the stack.
Parameters:
element (any) :The element to be inserted at the top of the stack.
Returns:
list: The updated list of stack elements.
"""
Lists.handle_insert(self, 0, element)
return self.elements
def pop(self):
"""
Removes and returns the element at the top of the stack.
Raises:
Exception: If the stack is empty.
Returns:
The element at the top of the stack.
"""
if len(self.elements) == 0:
raise Exception("Stack is empty")
return Lists.handle_pop(self)
def peek(self):
"""
Returns the element at the top of the stack without removing it.
Raises:
Exception: If the stack is empty.
Returns:
The element at the top of the stack.
"""
if len(self.elements) == 0:
raise Exception("Stack is empty")
return self.elements[0]
def size(self):
"""
Returns the number of elements in the stack.
Returns:
int: The number of elements in the stack.
"""
return len(self.elements)