I am learning python and have an assignment to better my understanding of "class" and using "stack."
The requirements are as follows:
-Define a class which implements stack for numerical values.
-Cannot use built-in pop function
-Function push should check if value is numerical
-Function print_stack should print values in stack, most recent (on top) first
-Function IsEmpty should return True if stack is empty, false otherwise
Here is my work so far:
class stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def isEmpty(self):
return (self.items == []) #can also use return not self i think?
def print_stack(self):
print self.items
This is my very first class in programming so I'm sorry if my understanding is poor. I'm not looking for anyone to outright write this for me. I really want to understand how to go about this and receive some pointers on what I need to do as well as what I am lacking in understanding if it is obvious.
My questions are as follows:
1) How can I test if I am pushing a numerical value? On first thought, could I use try/except?
2) What is the best way to go about creating a pop function without using the one that's built in? This is really giving me a hard time. From my understanding I need to write something that will retrieve the last item from the list and return it.
3) to test my code would I do something like this?
test = stack()
test.push(1)
test.print_stack()
test.pop() #whenever I learn how to make a pop function
test.isEmpty