0% found this document useful (0 votes)
19 views

Python Stacks

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python Stacks

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

CREATING AN ADT STACK IN PYTHON

class stack:
# Create our data properties
def __init__(self, size=8):
self.size = size # set size of array
self.stack = [None] * size # Create array of size length
self.top = -1 # first set the top to -1 (on startup)

# Create all our functions (is_empty, isFull, push, pop, etc)


# Check if stack is empty by comparing top to -1 (returns true or false)
def is_empty(self):
top =-1 return self.top == -1

# check if stack full by comparing variable.top to size (returns true or false)


def is_full(self):
return self.top == self.size - 1

# Add item to stack, first check if it is not empty


def push(self, item):
if self.is_full():
raise OverflowError("Stack is full!")

# increate top by 1 & add item to stack


self.top += 1
self.stack[self.top] = item

# Remove from stack and update .top


def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack!")

popped_value = self.stack[self.top]
self.stack[self.top] = None
self.top -= 1
return popped_value

# Return value on the top of the stack


def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack!")

return self.stack[self.top]

# Return entire stack array


def str(self):
return str(self.stack)
# The main program where we now use the stack datatype we created

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

print(stack)

# outputs -> [1, 2, 3, None, None, None, None, None]

print(stack.pop())

print(stack)

# outputs -> [1, 2, None, None, None, None, None, None]

stack.push(4)

print(stack.peek())

print(stack)

# outputs -> [1, 2, 4, None, None, None, None, None]

You might also like