Upload 2.py
Browse files
2.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Empty(Exception):
|
| 2 |
+
pass
|
| 3 |
+
class ArrayStack:
|
| 4 |
+
def __init__(self):
|
| 5 |
+
self._data = []
|
| 6 |
+
def __len__(self):
|
| 7 |
+
return len(self._data)
|
| 8 |
+
def is_empty(self):
|
| 9 |
+
return len(self._data) == 0
|
| 10 |
+
def push(self, e):
|
| 11 |
+
self._data.append(e)
|
| 12 |
+
print("The element", e, "is pushed successfully")
|
| 13 |
+
def top(self):
|
| 14 |
+
if self.is_empty():
|
| 15 |
+
raise Empty("Stack is Empty!")
|
| 16 |
+
return self._data[-1]
|
| 17 |
+
def pop(self):
|
| 18 |
+
if self.is_empty():
|
| 19 |
+
raise Empty("Stack is Empty!")
|
| 20 |
+
return self._data.pop()
|
| 21 |
+
print("\t Stack ADT Implementation")
|
| 22 |
+
print("\t---------------------------------")
|
| 23 |
+
stack = ArrayStack()
|
| 24 |
+
while True:
|
| 25 |
+
print("\n\t Stack Operations:")
|
| 26 |
+
|
| 27 |
+
print("1 - Push")
|
| 28 |
+
print("2 - Pop")
|
| 29 |
+
print("3 - Top element")
|
| 30 |
+
print("4 - Length of stack")
|
| 31 |
+
print("5 - Is empty")
|
| 32 |
+
print("6 - Display stack elements")
|
| 33 |
+
print("7 - Exit")
|
| 34 |
+
ch = int(input("Enter your choice: "))
|
| 35 |
+
try:
|
| 36 |
+
if ch == 1:
|
| 37 |
+
e = int(input("Enter the element: "))
|
| 38 |
+
stack.push(e)
|
| 39 |
+
elif ch == 2:
|
| 40 |
+
t = stack.pop()
|
| 41 |
+
print("The element", t, "is popped successfully")
|
| 42 |
+
elif ch == 3:
|
| 43 |
+
t = stack.top()
|
| 44 |
+
print("The top element in the stack is", t)
|
| 45 |
+
elif ch == 4:
|
| 46 |
+
print("Number of elements in stack is", len(stack))
|
| 47 |
+
elif ch == 5:
|
| 48 |
+
if stack.is_empty():
|
| 49 |
+
print("Stack is Empty")
|
| 50 |
+
else:
|
| 51 |
+
print("Stack is not empty")
|
| 52 |
+
elif ch == 6:
|
| 53 |
+
if stack.is_empty():
|
| 54 |
+
print("Stack is empty")
|
| 55 |
+
|
| 56 |
+
else:
|
| 57 |
+
print("Elements in stack (Top to Bottom):")
|
| 58 |
+
for i in range(len(stack) - 1, -1, -1):
|
| 59 |
+
print("|", stack._data[i], "|")
|
| 60 |
+
print("-------------")
|
| 61 |
+
elif ch == 7:
|
| 62 |
+
print("Program exited")
|
| 63 |
+
break
|
| 64 |
+
else:
|
| 65 |
+
print("Invalid choice")
|
| 66 |
+
except Empty as e:
|
| 67 |
+
print(e)
|
| 68 |
+
|
| 69 |
+
except ValueError:
|
| 70 |
+
print("Please enter a valid number")
|