Amazing-Python-Scripts

Форк
0
75 строк · 1.6 Кб
1
''' 
2
STACK
3
    LIFO
4

5
All push and pop operations are to/from the top of the stack
6
    PUSH an item onto the stack
7
    POP an item off of the stack
8
    PEEK to get item on top of stack, without removing it
9
    CLEAR all items from stack
10

11
STACK USE CASE
12
Undo Command : track which command have been executed. Pop last command off the command stack to undo it
13
Calling Function: Function Calling in any programming language is managed using stack
14

15
Stack Class in Python:
16
    list
17
    collections.deque
18
    queue.LifoQueue
19

20
BigO of stack:
21
    Push/Pop element -----> O(1)
22
    Search element by value -----> O(n)
23

24
'''
25

26
''' CLASS STACK() '''
27

28

29
class Stack():
30
    def __init__(self):
31
        self.stack = list()
32

33
    def push(self, item):
34
        self.stack.append(item)
35

36
    def pop(self):
37
        if len(self.stack) > 0:
38
            return self.stack.pop()
39

40
    def peek(self):
41
        if len(self.stack) > 0:
42
            return self.stack[len(self.stack)-1]
43
        else:
44
            return None
45

46
    def __str__(self):
47
        return str(self.stack)
48

49

50
''' CLASS STACK() END '''
51

52
stack = list()
53
# .append method to append items to the stack
54
stack.append(1)
55
stack.append(4)
56
stack.append(9)
57
stack.append(16)
58
print(f"Stack is {stack}", end="\n\n")
59
stack.pop()
60
print(f"Deleted Last item of Stack (LIFO) {stack}", end="\n\n")
61

62
# Calling Stack() class
63
stack = Stack()
64

65
stack.push(1)
66
stack.push(2)
67
stack.push(3)
68
stack.push('B')
69

70
print(f"New Stack is {stack}")
71
print(f"Deleted item is {stack.pop()}")
72
print(f"Seek is at {stack.peek()}")
73

74

75
# TODO: Stack continue ( https://youtu.be/kQDxmjfkIKY?t=3077 )
76

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.