-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
A_implementation.py
98 lines (73 loc) · 2.01 KB
/
A_implementation.py
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
87
88
89
90
91
92
93
94
95
96
97
98
# method1
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = Node("head")
self.size = 0
def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
cur = cur.next
return out[:-3]
def getSize(self):
return self.size
def isEmpty(self):
return self.size == 0
def peek(self):
if self.isEmpty():
raise Exception("Peeking from an empty stack")
return self.head.next.value
def push(self, value):
node = Node(value)
node.next = self.head.next
self.head.next = node
self.size += 1
def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
remove = self.head.next
self.head.next = self.head.next.next
self.size -= 1
return remove.value
def method2():
stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print("Initial stack")
print(stack)
print("\nElements poped from stack:")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("\nStack after elements are poped:")
return stack
def method3():
from collections import deque
stack = deque()
stack.append("a")
stack.append("b")
stack.append("c")
print("Initial stack:")
print(stack)
print("\nElements poped from stack:")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("\nStack after elements are poped:")
return stack
if __name__ == "__main__":
"""
from timeit import timeit
stack_ = Stack()
for i in range(1, 11):
stack_.push(i)
print(timeit(lambda: f"Stack: {stack_}", number=10000)) # 0.0233232409991615
print(timeit(lambda: method2(), number=10000)) # 0.8586116020014742
print(timeit(lambda: method3(), number=10000)) # 0.9672414289998414
"""