Stacks / Constrains
Stacks are simply arrays with restrictions.
We can thing at a stack as a list displayed vertically.
Just like a stack of dishes, you can look only at the face of the top dish.
A handy acronym to describe stack operations is LIFO (last in, first out).
Lists / Python
In Python the stack is
build-in data type.
It is called
list and has append() and pop() methods.
mystack = []
mystack.append(1)
mystack.append(2)
mystack.append(3)
print("Stack after insertion =", mystack)
front = mystack.pop()
print("Stack after deletion =", mystack)
print("Popped element, front =", front)
Create Stack
Most programming
languages doesn't come with a built-in stack data type.
Let's create a stack to see how it
works internaly.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items += [item]
def pop(self):
item = self.items[-1]
self.items = self.items[:-1]
return item
def read(self):
return self.items[-1]
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Read from stack top =", stack.read())
popped = stack.pop()
print("Remove from stack top =",
