Stack%2C Queue data structures - AndrewMZ6/Python_cheat_sheet GitHub Wiki
Stack is LIFO (last in first out) data structure which can be made using python list
and two of it's methods - append
and 'pop`.
Adding to stack:
stack = []
stack.append('some_string')
stack.append(90)
Getting and removing element from the end of the stack
elem = stack.pop()
Queue is FIFO (first in first out) data structure is similar to stack but getting elements must be done from the beginning of the list
queue = []
queue.append('some_string')
queue.append(90)
Getting and removing element from the beginning of the queue
elem = queue.pop(0)
pop(0)
returns the element with index 0
and removes it from queue
object.
Here's my implementation of Queue
as class
class Queue:
"""
adding elements:
[] <- 73
[73]
[73] <- 771
[73, 771]
[73, 771] <- 80
[73, 771, 80]
getting elements:
[73, 771, 80] -> 73
[771, 80]
[771, 80] -> 771
[80]
[80] -> 80
[]
"""
def __init__(self):
self.queue = []
def add_el(self, *args):
self.queue.extend(args)
def get_el(self):
return self.queue.pop(0)
def __str__(self):
return str(self.queue)
q = Queue()
q.add_el(1, 0, 'goo', (1, 2, 3))
print(f"q = {q}")
v = q.get_el()
print(f"q = {q}, v = {v}")
v = q.get_el()
print(f"q = {q}, v = {v}")
v = q.get_el()
print(f"q = {q}, v = {v}")
v = q.get_el()
print(f"q = {q}, v = {v}")
v = q.get_el()
print(f"q = {q}, v = {v}")
output:
q = [1, 0, 'goo', (1, 2, 3)]
q = [0, 'goo', (1, 2, 3)], v = 1
q = ['goo', (1, 2, 3)], v = 0
q = [(1, 2, 3)], v = goo
q = [], v = (1, 2, 3)
Traceback (most recent call last):
File "E:\Code\Python\test20.py", line 52, in <module>
v = q.get_el()
File "E:\Code\Python\test20.py", line 30, in get_el
return self.queue.pop(0)
IndexError: pop from empty list
Changing method's get_el
body to return self.queue.pop()
gives class representating stack