File size: 2,219 Bytes
480765c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class Empty(Exception): 
    pass 
class ArrayStack: 
    def __init__(self): 
        self._data = [] 
    def __len__(self): 
        return len(self._data) 
    def is_empty(self): 
        return len(self._data) == 0 
    def push(self, e): 
        self._data.append(e) 
        print("The element", e, "is pushed successfully") 
    def top(self): 
        if self.is_empty(): 
            raise Empty("Stack is Empty!") 
        return self._data[-1] 
    def pop(self): 
        if self.is_empty(): 
            raise Empty("Stack is Empty!") 
        return self._data.pop() 
print("\t Stack ADT Implementation") 
print("\t---------------------------------") 
stack = ArrayStack() 
while True: 
    print("\n\t Stack Operations:") 
 
    print("1 - Push") 
    print("2 - Pop") 
    print("3 - Top element") 
    print("4 - Length of stack") 
    print("5 - Is empty") 
    print("6 - Display stack elements") 
    print("7 - Exit") 
    ch = int(input("Enter your choice: ")) 
    try: 
        if ch == 1: 
            e = int(input("Enter the element: ")) 
            stack.push(e) 
        elif ch == 2:  
            t = stack.pop() 
            print("The element", t, "is popped successfully") 
        elif ch == 3: 
            t = stack.top() 
            print("The top element in the stack is", t) 
        elif ch == 4: 
            print("Number of elements in stack is", len(stack)) 
        elif ch == 5: 
            if stack.is_empty(): 
                print("Stack is Empty") 
            else: 
                print("Stack is not empty") 
        elif ch == 6: 
            if stack.is_empty(): 
                print("Stack is empty") 
 
            else: 
                print("Elements in stack (Top to Bottom):") 
                for i in range(len(stack) - 1, -1, -1): 
                    print("|", stack._data[i], "|") 
                    print("-------------") 
        elif ch == 7: 
            print("Program exited") 
            break 
        else: 
            print("Invalid choice") 
    except Empty as e: 
        print(e) 
 
    except ValueError: 
        print("Please enter a valid number")