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.
# Empty list to represent a stack
mystack = []
# Push elements onto the stack
mystack.append(1)
mystack.append(2)
mystack.append(3)
# Output stack
print("Stack after insertion =", mystack)
# Pop element from the stack
front = mystack.pop()
# Output stack
print("Stack after deletion =", mystack)
print("Popped element, front =", front)
"""
Stack after insertion = [1, 2, 3]
Stack after deletion = [1, 2]
Popped element, front = 3
"""
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] # remove the last from the list
return item
def read(self):
return self.items[-1]
# New stack
stack = Stack()
# Push elements onto the stack
stack.push(1)
stack.push(2)
stack.push(3)
# Read from stack
print("Read from stack top =", stack.read())
# Pop from stack
popped = stack.pop()
print("Remove from stack top =",
"""
Read from stack top = 3
Remove from stack top = 3
New top = 2
"""
Last update: 353 days ago