xxxxxxxxxx
class Stack():
def __init__(self):
self._stack = []
def push(self, item):
self._stack.append(item)
def isEmpty(self):
return not self._stack
def pop(self):
if(self.isEmpty()):
return None
return self._stack.pop()
def peek(self):
if(self.isEmpty()):
return None
return self._stack[-1]
def size(self):
return len(self._stack)
def __str__(self):
toString = ""
for el in self._stack:
toString += f"{el} "
return toString
xxxxxxxxxx
from collections import deque
the_stack = deque()
# this function can serve as push
the_stack.append("data")
print(the_stack.pop()) # -> data
# Check out the documents for more features coming when using that dedicated
# builtin.
# About deque: Deques are a generalization of stacks and queues
# (the name is pronounced “deck” and is short for “double-ended queue”).
# Deques support thread-safe, memory efficient appends and pops from either
# side of the deque with approximately the same O(1) performance in either
# direction.
xxxxxxxxxx
class Stack:
def __init__(self, stack=[]):
self.stack = list(stack)
def push(self, item):
self.stack.insert(0, item)
return self.stack
def pop(self):
item_0 = self.stack[0]
del self.stack[0]
return item_0
def __repr__(self):
return f"{self.stack}"
stack = Stack() # or add a list value, doesn't matter
stack.push(5)
stack.push("10")
print(stack.pop()) # 10
print(stack.pop()) # 5
xxxxxxxxxx
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
def peek(self):
if not self.is_empty():
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.peek()) # Output: 2
print(stack.size()) # Output: 2