Stack
In [1]:
# Stack with Integers
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def is_empty(self):
return len(self.items) == 0
def __str__(self):
return str(self.items)
def __repr__(self):
return f"Stack({self.items})"
int_stack = Stack()
int_stack.push(1)
int_stack.push(2)
int_stack.push(3)
print(int_stack)
print(int_stack.pop())
print(int_stack)
print(int_stack.pop())
print(int_stack)
print(int_stack.pop())
print(int_stack)
[1, 2, 3] 3 [1, 2] 2 [1] 1 []
In [2]:
# Stack with Strings
class StringStack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def is_empty(self):
return len(self.items) == 0
def __str__(self):
return str(self.items)
def __repr__(self):
return f"StringStack({self.items})"
str_stack = StringStack()
str_stack.push("apple")
str_stack.push("banana")
str_stack.push("cherry")
print(str_stack)
print(str_stack.pop())
print(str_stack)
print(str_stack.pop())
print(str_stack)
print(str_stack.pop())
print(str_stack)
['apple', 'banana', 'cherry'] cherry ['apple', 'banana'] banana ['apple'] apple []
In [3]:
# Stack with Dictionaries (Healthcare Data)
class DictStack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def is_empty(self):
return len(self.items) == 0
def __str__(self):
return str(self.items)
def __repr__(self):
return f"DictStack({self.items})"
healthcare_stack = DictStack()
healthcare_stack.push({"patient_id": 1, "name": "John Doe", "age": 30})
healthcare_stack.push({"patient_id": 2, "name": "Jane Smith", "age": 25})
print(healthcare_stack)
print(healthcare_stack.pop())
print(healthcare_stack)
print(healthcare_stack.pop())
print(healthcare_stack)
print(healthcare_stack.pop())
print(healthcare_stack)
[{'patient_id': 1, 'name': 'John Doe', 'age': 30}, {'patient_id': 2, 'name': 'Jane Smith', 'age': 25}]
{'patient_id': 2, 'name': 'Jane Smith', 'age': 25}
[{'patient_id': 1, 'name': 'John Doe', 'age': 30}]
{'patient_id': 1, 'name': 'John Doe', 'age': 30}
[]
None
[]
In [4]:
# Generic Stack
class GenericStack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def is_empty(self):
return len(self.items) == 0
def __str__(self):
return str(self.items)
def __repr__(self):
return f"GenericStack({self.items})"
generic_stack = GenericStack()
generic_stack.push(1)
generic_stack.push("apple")
generic_stack.push({"key": "value"})
print(generic_stack)
print(generic_stack.pop())
print(generic_stack)
print(generic_stack.pop())
print(generic_stack)
print(generic_stack.pop())
print(generic_stack)
[1, 'apple', {'key': 'value'}]
{'key': 'value'}
[1, 'apple']
apple
[1]
1
[]
