-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathStack.py
More file actions
executable file
·86 lines (73 loc) · 1.96 KB
/
Stack.py
File metadata and controls
executable file
·86 lines (73 loc) · 1.96 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
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
class Stack(object):
"""Stack implementation using array implementation.
Args:
limit (int): size of the stack
"""
def __init__(self, limit=10):
self.limit = limit
self.stk = []
def is_empty(self):
"""Check for the stcak to be empty
"""
return self.stk == []
def is_full(self):
"""Check for the stcak to be full
"""
return self.length() == self.limit
def length(self):
"""return the size of the stack
"""
return len(self.stk)
def push(self, item):
"""push operation of stack
Args:
item (any): element to insert
"""
if self.length() >= self.limit:
print("Stack OverFlow")
return
self.stk.append(item)
print("Stack after push", self.stk)
def pop(self):
"""Pop operation of stack
Returns:
value at top
"""
if self.length() <= 0:
print("Stack Underflow")
return None
return self.stk.pop()
def peek(self):
"""Returns value at top of the stack
"""
if self.length() <= 0:
print("Stack Underflow")
return None
return self.stk[-1]
def __str__(self):
return f"Stack: {self.stk}"
if __name__ == "__main__":
s = Stack()
while True:
print("\n1. View Stack")
print("2. Push")
print("3. Pop")
print("4. Peek")
print("5. Size of Stack")
print("0. Exit")
ch = int(input("Enter your choice"))
if ch == 0:
break
elif ch == 1:
print(s)
elif ch == 2:
value = input("Enter a value to push: ")
s.push(value)
elif ch == 3:
print(s.pop())
elif ch == 4:
print(s.peek())
elif ch == 5:
print(s.length())
else:
print("Please Enter valid choice")