1. Stack using Python List
In [1]:
Copied!
class Stack:
def __init__(self):
self.items = []
self.__top = -1
def is_empty(self):
return self.__top == -1
# return len(self.items) == 0
# return self.items == []
def peek(self):
if self.is_empty():
print("Stack is empty, nothing to peek()")
else:
print("<Element: %s>" % self.items[-1])
def __repr__(self):
items = []
for i in range(len(self.items) - 1, 0, -1):
if i == self.__top:
items.append("[Top: %s]" % self.items[i])
else:
items.append("[%s]" % self.items[i])
return ", ".join(items)
def __iter__(self):
for i in range(len(self.items) - 1, 0, -1):
yield self.items[i]
def __len__(self):
return len(self.items)
def push(self, data):
print("Inserting: {} into the stack".format(data))
self.items.append(data)
self.__top += 1
def pop(self):
if self.is_empty():
print("Stack is empty, nothing to pop()")
else:
data = self.items.pop()
print("Removing: {} from top of the stack".format(data))
self.__top -= 1
class Stack:
def __init__(self):
self.items = []
self.__top = -1
def is_empty(self):
return self.__top == -1
# return len(self.items) == 0
# return self.items == []
def peek(self):
if self.is_empty():
print("Stack is empty, nothing to peek()")
else:
print("" % self.items[-1])
def __repr__(self):
items = []
for i in range(len(self.items) - 1, 0, -1):
if i == self.__top:
items.append("[Top: %s]" % self.items[i])
else:
items.append("[%s]" % self.items[i])
return ", ".join(items)
def __iter__(self):
for i in range(len(self.items) - 1, 0, -1):
yield self.items[i]
def __len__(self):
return len(self.items)
def push(self, data):
print("Inserting: {} into the stack".format(data))
self.items.append(data)
self.__top += 1
def pop(self):
if self.is_empty():
print("Stack is empty, nothing to pop()")
else:
data = self.items.pop()
print("Removing: {} from top of the stack".format(data))
self.__top -= 1
In [2]:
Copied!
stack = Stack()
stack = Stack()
In [3]:
Copied!
for i in range(0, 6):
stack.push(i)
for i in range(0, 6):
stack.push(i)
Inserting: 0 into the stack Inserting: 1 into the stack Inserting: 2 into the stack Inserting: 3 into the stack Inserting: 4 into the stack Inserting: 5 into the stack
In [4]:
Copied!
stack.pop()
stack.pop()
Removing: 5 from top of the stack
In [5]:
Copied!
stack.is_empty()
stack.is_empty()
Out[5]:
False
In [6]:
Copied!
stack.peek()
stack.peek()
<Element: 4>
In [7]:
Copied!
stack
stack
Out[7]:
[Top: 4], [3], [2], [1]
In [8]:
Copied!
for i in stack:
print(i)
for i in stack:
print(i)
4 3 2 1
In [9]:
Copied!
len(stack)
len(stack)
Out[9]:
5
In [10]:
Copied!
for _ in range(10):
stack.pop()
for _ in range(10):
stack.pop()
Removing: 4 from top of the stack Removing: 3 from top of the stack Removing: 2 from top of the stack Removing: 1 from top of the stack Removing: 0 from top of the stack Stack is empty, nothing to pop() Stack is empty, nothing to pop() Stack is empty, nothing to pop() Stack is empty, nothing to pop() Stack is empty, nothing to pop()
In [ ]:
Copied!