Stack data structure in python - python

I have 2 issues with the code below:
push(o) throws an exception TypeError: can only assign an iterable.
Should I throw an exception if pop() is invoked on an empty stack ?
class Stack(object):
def __init__(self):
self.storage = []
def isEmpty(self):
return len(self.storage) == 0
def push(self,p):
self.storage[:0] = p
def pop(self):
"""issue: throw exception?"""
return None

No need to jump through these loops, See 5.1.1 Using Lists as Stacks
If you insist on having methods isEmpty() and push() you can do:
class stack(list):
def push(self, item):
self.append(item)
def isEmpty(self):
return not self

You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.
class Stack:
def __init__(self):
self.__storage = []
def isEmpty(self):
return len(self.__storage) == 0
def push(self,p):
self.__storage.append(p)
def pop(self):
return self.__storage.pop()
This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.

I won't talk about the list structure as that's already been covered in this question. Instead I'll mention my preferred method for dealing with stacks:
I always use the Queue module. It supports FIFO and LIFO data structures and is thread safe.
See the docs for more info. It doesn't implement a isEmpty() function, it instead raises a Full or Empty exception if a push or pop can't be done.

Stack follows LIFO mechanism.You can create a list and do a normal append() to append the element to list and do pop() to retrieve the element out of the list which you just inserted.

Here is an example for stack class
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def isEmpty(self):
return len(self.items) == 0

class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self , item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
Create a stack
To create a new stack we can simply use Stack()
for example:
s=Stack()
"s" is the name of new stack
isEmpty
By using isEmpty() we can check our stack is empty or not
for example:
we have two stacks name s1=(0,1,4,5,6) and s2=()
if we use print(s1.isEmpty()) it will return False
if we use print(s2.isEmpty()) it will return True
push
By using push operation we can add items to top of the stack
we can add "6" to the stack name "s" using
s.push(6)
pop
we can use pop operation to remove and return the top item of a stack
if there is a stack name "s" with n amount items (n>0)
we can remove it's top most item by using
s.pop()
size
This operation will return how many items are in the stack
if there is a stack name "s" s=(1,2,3,4,5,3)
print(s.size())
will return "6"
peek
This operation returns the top item without removing it
print(s.peek())
"we can print items of the stack using print(s.items)"

class Stack:
def __init__(self):
self.stack = []
def pop(self):
if self.is_empty():
return None
else:
return self.stack.pop()
def push(self, d):
return self.stack.append(d)
def peek(self):
if self.is_empty():
return None
else:
return self.stack[-1]
def size(self):
return len(self.stack)
def is_empty(self):
return self.size() == 0

class stack:
def __init__(self,n):##constructor
self.no = n ##size of stack
self.Stack = [] ##list for store stack items
self.top = -1
def push(self):##push method
if self.top == self.no - 1 :##check full condition
print("Stack Overflow.....")
else:
n = int(input("enter an element :: "))
self.Stack.append(n) ## in list add stack items use of append method
self.top += 1##increment top by 1
def pop(self):## pop method
if self.top == -1: #check empty condition
print("Stack Underflow....")
else:
self.Stack.pop()## delete item from top of stack using pop method
self.top -= 1 ## decrement top by 1
def peep(self): ##peep method
print(self.top,"\t",self.Stack[-1]) ##display top item
def disp (self): #display method
if self.top == -1:# check empty condition
print("Stack Underflow....")
else:
print("TOP \tELEMENT")
for i in range(self.top,-1,-1): ## print items and top
print(i," \t",self.Stack[i])
n = int(input("Enter Size :: ")) # size of stack
stk = stack(n) ## object and pass n as size
while(True): ## loop for choice as a switch case
print(" 1: PUSH ")
print(" 2: POP ")
print(" 3: PEEP ")
print(" 4: PRINT ")
print(" 5: EXIT ")
option = int(input("enter your choice :: "))
if option == 1:
stk.push()
elif option == 2:
stk.pop()
elif option == 3:
stk.peep()
elif option == 4:
stk.disp()
elif option == 5:
print("you are exit!!!!!")
break
else:
print("Incorrect option")

Related

Max stack in python - 2 stacks solution

I am trying to build a max stack in python, I am not sure what I am doing wrong.
Here is the question>
Design a max stack data structure that supports the stack operations
and supports finding the stack's maximum element.
Implement the MaxStack class:
MaxStack() Initializes the stack object.
void push(int x) Pushes element x onto the stack.
int pop() Removes the element on top of the stack and returns it.
int top() Gets the element on the top of the stack without removing it.
int peekMax() Retrieves the maximum element in the stack without removing it.
int popMax() Retrieves the maximum element in the stack and removes it.
If there is more than one maximum element, only remove the top-most one.
class MaxStack:
def __init__(self):
self.stack = []
self.stack_max = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.stack_max or x > self.stack_max[-1][0]:
self.stack_max.append([x, 1])
elif x == self.stack_max[-1][0]:
self.stack_max[-1][1] += 1
else:
self.stack_max.append(self.stack_max[-1])
def pop(self) -> int:
if not self.stack_max or self.stack:
return
if self.stack_max[-1][0] == self.stack[-1]:
self.stack_max[-1][1] -= 1
if self.stack_max[-1][1] == 0:
del self.stack_max[-1]
return self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def peekMax(self) -> int:
if self.stack_max:
return self.stack_max[-1][0]
def popMax(self) -> int:
if self.stack_max:
return self.stack_max.pop()[0]
Example code:
obj = MaxStack()
obj.push(6)
param_2 = obj.pop()
param_3 = obj.top()
param_4 = obj.peekMax()
param_5 = obj.popMax()
Input :
["MaxStack","push","push","push","top","popMax","top","peekMax","pop","top"] [[],[5],[1],[5],[],[],[],[],[],[]]
Output:
[null,null,null,null,5,5,5,5,None,5]
Expected:
[null,null,null,null,5,5,1,5,1,5]
Reference: Leetcode 716. Max Stack
class MaxStack:
def __init__(self,value):#taking some value to avoid empty obj
self.stack=[value]
self.max_=[value,0]
self.length=1
def push(self,value):
self.stack.append(value)
self.length+=1
if value>self.max_[0]:
self.max_[0],self.max_[1]=value,self.length-1
def pop(self):
if self.length==0:
return
elif self.stack[-1]==self.max_[0]:
self.popMax()
else:
self.stack.pop()
self.length-=1
def top(self):
print(self.stack[-1])
def peekMax(self):
print(self.max_[0])
def popMax(self):
if self.length==0 or self.max_[1]==-1:
return
self.stack.pop(self.max_[1])
self.length-=1
self.max_[0],self.max_[1]=-1,-1
for i in range(self.length):
if self.stack[i]>self.max_[0]:
self.max_[0],self.max_[1] = self.stack[i],i
Sorry for the improper indentations, I tried a lot to fix it. Anyways this should work and I wanted to try it out on leetcode but it needs a login. Let me know if there is any issue.
To me, it seems a little confusing to track the count in the tuple of the value, when you could just continue adding to the max stack and counting them from the list if you need that.
class MaxStack:
def __init__(self):
self.stack = []
self.maxes = []
def push(self, n):
self.stack.append(n)
if not self.maxes or n >= max(self.maxes):
self.maxes.append(n)
def pop(self):
if self.stack:
val = self.stack.pop()
if val in self.maxes:
self.maxes.remove(val)
def top(self):
if self.stack:
return self.stack[-1]
def peek_max(self):
if self.maxes:
return self.maxes[-1]
def pop_max(self):
if self.maxes:
return self.maxes.pop()
Then if you need the count of the number of each, just use count():
def max_count(self):
if self.maxes:
return self.maxes.count(max(self.maxes))

stack class in Python

I have written the below code to implement the stack class instead of using the build in function, not sure if I have got it rigth. Can someone please check for me and advise if there is an error?
class DSAStack():
maxCap = 100
def __init__(self):
self.stack = []
self.count = 0
def isEmpty(self):
if self.count == 0:
return True
else:
return false
def isFull(self):
if self.count == maxCap:
return True
else:
return false
def push(self, item):
if self.isFull:
raise ('Stack is full...')
else:
self.stack[self.count] = item
self.count += 1
def pop(self):
self.topVal = self.top
self.stack[self.count - 1] = 0
self.count = self.count - 1
return self.topVal
def top(self):
if self.isEmpty:
raise ('Stack is empty...')
else:
self.top = self.stack[self.count - 1]
Firstly, you need not keep track of count. Accessing the length of the list will do that for you.
def __init__(self):
self.stack =[]
Now, your logic for isEmpty and isFull was alright, but since we are removing the self.count variable, here's how you'd go about it
def isEmpty(self):
return len(self.stack) == 0 #Directly return true or false
def isFull(self):
return len(self.stack) == maxCap #Directly return true or false
In your push function, there are a few things I'd like to point out.
First, you need to call the isFull function. So we need to add parentheses to it.
Secondly, you cant just raise ('Stack is full...'), you will get a TypeError: Exceptions must derive from BaseException. This basically means what you raise must be some type of error.
Lastly, you can't add a new element by doing self.stack[self.count]=item since you will get an IndexError
Here are the changes:
def push(self,item):
if self.isFull(): #Need to call the function, self.isFull is not a variable
raise Exception('Stack is full...') #Or any other type of error
else:
self.stack.append(item) #Adds new item to the end of self.stack
Now coming to the pop function, setting a value to zero in a list does not really get rid of it. And it can cause a lot of confusion, especially since we are using the len(self.stack) to implement this.
Here's how you would pop:
def pop(self):
if self.isEmpty():
raise Exception('Stack is empty...')
else:
return self.stack.pop() #List has a built-in pop method
So now we don't really need the top function. And that concludes that. Btw, in your top function, you have defined self.top = self.stack[self.count-1]
Giving the same name to a function and a variable is never really a good idea.
To implement the pop functionality yourself, you could do the following:
def pop(self):
if self.isEmpty():
raise Exception('Stack is empty...')
else:
topVal = self.stack[-1] #-1 gives you the last element
#if stack will contain objects instead of primitive data types, use self.stack[-1].copy()
del self.stack[-1] #Deletes the element
return topVal
Polishing your top function will be like this:
def top(self):
if self.isEmpty():
raise Exception('Stack is empty...')
else:
return self.stack[-1]
def pop(self):
topVal = self.top()
del self.stack[-1]
return topVal
Note how the top function is defined before the pop function.
Also, try to test the code out and resolving any issues.

I can only push two values onto the stack array?

I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
class Stack:
def __init__(self, data):
if data > 0:
self.stack = [0] * data
self.top = -1
self.stack[self.top] = self.stack[-1]
elif data <= 0:
self.stack = [0] * 10
self.top = -1
def showStack(self):
for i in self.stack:
print(i, end=" ")
return
def isEmpty(self):
return self.stack == []
def myEmpty(self): #complete this function
return # just a placeholder
def push(self, data):
self.stack.append(data)
def myPush(self, data):
if data == 0:
print("You did not enter a value.")
elif self.sizeStack() <= 10:
current = self.stack[stack.top]
self.stack[stack.top] = data
self.stack[stack.top - 1] = current
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def myPop(self): #complete this function
return # just a placeholder
def myPeek(self):
temp = self.top
return temp
def sizeStack(self):
return len(self.stack)
userVal = int(input("Enter the size of the stack: "))
stack = Stack(userVal)
while True:
print('\n1 display the stack')
print('2 add a value to the stack')
print('3 check the value at the top of the stack')
print('4 remove the value at the top of the stack')
print('5 check if the stack is empty')
print('99 quit')
option = int(input("Enter your choice: "))
if option == 1:
stack.showStack()
elif option == 2:
temp = int(input("Enter a number to add to the stack: "))
stack.myPush(temp)
elif option == 3:
print(stack.peek())
elif option == 99:
break
else:
print('Wrong option')
print
try defining a some customized functions that map to your list. Read up on customization here
class stack:
def __init__(self, data):
self.stack = [0] * data
self.top = -1
# whatever you want to do to init the list
def __str__(self): # replaces your showstack function now just use print(stack)
return self.stack
def __iter__(self): # creates an iterator you can use
return iter(self.stack)
def __len__(self): # replaces your sizestack function
return len(self.stack)
basically just adjust the methods you need.

Implementing Stacks and Queues using a Linked List

I'm trying to go over some previous homework problems in my computer science class with regards to Linked List. This question is really bothering me on how I should go about this, where it wants me to implement a "Stack" and a "Queue" class to go along using my Linked List class I made a while back. That is all the question states, so would I have to use my ListNode class which is this.
class ListNode(object):
def __init__(self, item = None, link = None):
'''creates a ListNode with the specified data value and link
post: creates a ListNode with the specified data value and link'''
self.item = item
self.link = link
How would I go about making a stack class that can push and pop? Would my code look like this or will I be way off?
from ListNode import ListNode
class LinkedStack(object):
def __init__(self, ListNode.item):
stack = []
def push(self,item):
self.append(ListNode.item)
self.size += 1
def isEmpty(self):
return not self
I just based that code off examples I have seen on this web page. Any help to make a simple stack class based off a linked list? For some reason it wants me to test my code using this class that was given to me which was this.
def isPalindrome(phrase):
forward = Queue()
reverse = Stack()
extractLetters(phrase, forward, reverse)
return sameSequence(forward, reverse)
#------------------------------------------------------------
def extractLetters(phrase, q, s):
for ch in phrase:
if ch.isalpha():
ch = ch.lower()
q.enqueue(ch)
s.push(ch)
#------------------------------------------------------------
def sameSequence(q, s):
while q.size() > 0:
ch1 = q.dequeue()
ch2 = s.pop()
if ch1 != ch2:
return False
return True
Thanks to whoever helps me in advance!
one way to create stack using python list is using list's append & pop functions.
Example stack class:
class stack(object):
def __init__(self):
self.data = []
def pop(self):
if self.isEmpty():
print "Nothing to remove from stack"
return None
return self.data.pop()
def push(self, item):
self.data.append(item)
def isEmpty(self):
if len(self.data) == 0:
return True
return False
s = stack()
s.push(1)
s.push(2)
s.push(3)
print s.pop()
print s.pop()
print s.pop()
print s.pop()
Output:
3
2
1
Nothing to remove from stack
None

Ambiguous behavior of using "not" and "bool" together on an empty list in Python

In this simple implementation of Stack using Python lists. I have a small method to check if the stack is empty (list empty). I am using this method as a check condition for pop method. The pop method should raise an exception when trying to pop an empty stack. For some reason, this doesn't seem to work. Am I missing something here? Please help!
__author__ = '#arun'
# Stack simple implementation using Python list
class Stack(object):
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def is_empty(self):
return not bool(self.items)
def pop(self):
print self.is_empty()
if self.is_empty: # if not stack is empty
return self.items.pop()
else:
raise Exception("Stack Empty!")
def peek(self):
return self.items[-1]
def get_size(self):
return len(self.items)
if __name__ == '__main__':
stack = Stack()
print stack.get_size()
stack.push(23)
stack.push(3)
print stack.get_size()
print stack.pop()
print stack.pop()
print stack.get_size()
#print stack.pop()
Output:
0
2
False
3
False
23
0
Why is pop() method popping out elements when is_empty() is returning False?!
if self.is_empty:
will always evaluate to True, since it is a Truthy value. You need to call the function like this
if self.is_empty():
And a suggestion: You might want to pop the values only when is_empty() is False, like this
if not self.is_empty():

Categories

Resources