Amazing-Python-Scripts
75 строк · 1.6 Кб
1'''
2STACK
3LIFO
4
5All push and pop operations are to/from the top of the stack
6PUSH an item onto the stack
7POP an item off of the stack
8PEEK to get item on top of stack, without removing it
9CLEAR all items from stack
10
11STACK USE CASE
12Undo Command : track which command have been executed. Pop last command off the command stack to undo it
13Calling Function: Function Calling in any programming language is managed using stack
14
15Stack Class in Python:
16list
17collections.deque
18queue.LifoQueue
19
20BigO of stack:
21Push/Pop element -----> O(1)
22Search element by value -----> O(n)
23
24'''
25
26''' CLASS STACK() '''
27
28
29class Stack():
30def __init__(self):
31self.stack = list()
32
33def push(self, item):
34self.stack.append(item)
35
36def pop(self):
37if len(self.stack) > 0:
38return self.stack.pop()
39
40def peek(self):
41if len(self.stack) > 0:
42return self.stack[len(self.stack)-1]
43else:
44return None
45
46def __str__(self):
47return str(self.stack)
48
49
50''' CLASS STACK() END '''
51
52stack = list()
53# .append method to append items to the stack
54stack.append(1)
55stack.append(4)
56stack.append(9)
57stack.append(16)
58print(f"Stack is {stack}", end="\n\n")
59stack.pop()
60print(f"Deleted Last item of Stack (LIFO) {stack}", end="\n\n")
61
62# Calling Stack() class
63stack = Stack()
64
65stack.push(1)
66stack.push(2)
67stack.push(3)
68stack.push('B')
69
70print(f"New Stack is {stack}")
71print(f"Deleted item is {stack.pop()}")
72print(f"Seek is at {stack.peek()}")
73
74
75# TODO: Stack continue ( https://youtu.be/kQDxmjfkIKY?t=3077 )
76