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
Related
I've created my Node and Stack classes, but I can't figure out how I can display the repr in the Stack class in order to be able to print all items currently in the stack? I've been trying to concatenate the nodes but I'm not sure how since the Stack() doesn't allow iterating through the way a list does?
The stack works as it should, I just don't know how to display it's contents?
Here is my code:
class Stack:
class Node:
def __init__(self, elem, next):
self.elem = elem
self.next = next
def __repr__(self):
return str(self.elem)
def __init__(self):
self._stack = None
self._size = 0
def __repr__(self):
# *Not sure how to implement this properly*
s = ''
for i in range(self._size):
last = self._stack.elem
s += (str(last))+ ', '
self._stack.elem = self._stack.next
return
def push(self, elem):
if self._stack == None:
self._stack = self.Node(elem, None)
self._size += 1
else:
self._stack = self.Node(elem, self._stack)
self._size += 1
def pop(self):
if self._stack == None:
raise Exception ('This Stack is empty!')
else:
last = self._stack.elem
self._stack = self._stack.next
self._size -= 1
return last
def top(self):
return self._stack.elem
def isEmpty(self):
return self._size == 0
Example:
s= Stack()
s.push(4)
s.push(9)
s.push("joe")
s
joe, 9, 9,
Thank you in advance.
A way simpler implementation that avoids all the problems and pitfalls of your solution:
from typing import Iterable, Any
class Stack:
def __init__(self, xs: Iterable = None):
self._items = [] if xs is None else list(xs)
def push(self, elem: Any):
self._items.append(elem)
def pop(self) -> Any:
return self._items.pop()
def top(self) -> Any:
return self._items[-1]
def isEmpty(self) -> bool:
return not self._items
def __repr__(self) -> str:
typename = type(self).__name__
return f'{typename}({self._items})'
def __str__(self) -> str:
return ', '.join(str(x) for x in self._items)
s = Stack()
s.push(4)
s.push(9)
s.push("joe")
print(s)
print(repr(s))
But note that there's little use to a class like this over just using a list like a stack to begin with.
The output:
4, 9, joe
Stack([4, 9, 'joe'])
Note that this has the top element at the end, you could reverse it if you like of course.
If you insist on a working __repr__ for your specific implementation, using __repr__ as you intend in a non-standard way, something like this would work:
def __repr__(self):
p = self._stack
elems = []
while p is not None:
elems.append(p.elem)
p = p.next
return ', '.join(elems)
But note that there's several other issues with your implementation, other than this not being a correct __repr__, as previously pointed out here and in the comments. Your 'node' has a __repr__ which just returns its element value (which isn't a valid representation at all in most cases); you seem to be using __repr__ where you're really after __str__.
If this were an assignment in programming class, I'm not sure I'd award a passing grade, depending on what the aim was.
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))
so i am a bit confused as to how to attack the StackList and Node portion of this homework.. I barely have any programming experience, and after a full day of struggling I finally understood StackArray. But I also need to understand how I can implement the same functions into a LinkedList... Here are the instructions in case I cant be clear ..
The goal of this project is to implement the Stack Abstract Data Type using the built in List construct in
Python and the Stack ADT using the simple linked data structure covered in class.
As discussed in class you are to allocate a list of size stack_capacity and use this to store the items in the
stack. Since Lists in python expand when more storage is needed you will have to provide a mechanism to
prevent the list inside your stack from growing. This really prevents the stack from growing if the user only
accesses it through the given interface but that is fine for the purposes of this exercise. (This prevents the stack
from using more space that a user might want. Think of this as a requirement for an application on a small
device than has very limited storage.) In the case when a user attempts to push an item on to a full stack, your
push function (method) should raise an IndexError. Similarly if a user tries to pop an empty, your pop function
(method) should raise an IndexError.
tly
class StackArray:
"""Implements an efficient last-in first-out Abstract Data Type using a Python List"""
def __init__(self, capacity):
"""Creates and empty stack with a capacity"""
self.capacity = capacity # this is example for list implementation
self.items = [None]*capacity # this is example for list implementation
self.num_items = 0 # this is example for list implementation
def is_empty(self):
"""Returns true if the stack self is empty and false otherwise"""
def is_full(self):
"""Returns true if the stack self is full and false otherwise"""
def push(self, item):
def pop(self):
def peek(self):
def size(self):
"""Returns the number of elements currently in the stack, not the capacity"""
Submit to two files:
• stacks.py containing a list based implementation of stack and a linked implementation of stack. The
classes must be called: StackArray and StackLinked . Both implementations should follow the above
specification and be thoroughly tested.
• test_stacks.py contains your set of tests to ensure you classes work correctly
So far this is what I have come up with
class StackArray:
"""Implements an efficient last-in first-out Abstract Data Type using a Python List"""
def __init__(self, capacity):
"""Creates and empty stack with a capacity"""
self.capacity = capacity # this is example for list implementation
self.items = [None]*capacity # this is example for list implementation
self.num_items = 0 # this is example for list implementation
def is_empty(self):
"""Returns true if the stack self is empty and false otherwise"""
return self.num_items == 0
def is_full(self):
"""Returns true if the stack self is full and false otherwise"""
return self.num_items == self.capacity
def push(self, item):
self.num_items += 1
self.items[self.num_items - 1] = item
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
"""Returns the number of elements currently in the stack, not the capacity"""
return self.num_items
class Node:
# ? ?
# nodes have 2 parts to them data and pointer. Pointer always points to the data of previous
class StackLinkList:
def __init__(self, capacity):
"""Creates and empty stack with a capacity"""
self.capacity = capacity # this is example for list implementation
self.items = [None] * capacity # this is example for list implementation
self.num_items = 0 # this is example for list implementation
def is_empty(self):
"""Returns true if the stack self is empty and false otherwise"""
def is_full(self):
"""Returns true if the stack self is full and false otherwise"""
def push(self, item):
def pop(self):
def peek(self):
def size(self):
"""Returns the number of elements currently in the stack, not the capacity"""
And these are my testcases
import unittest
from stacks import *
class TestCase(unittest.TestCase):
# testing an empty Array
def test_if_empty(self):
s1 = StackArray(3) #[none,none,none]
self.assertTrue(s1.is_empty()) # Should be True
def test_if_not_empty(self):
s1 = StackArray(4) #[none,none,none,none]
s1.push(2) #[2,none,none,none]
s1.push(3) #[2,3,none,none]
s1.push(4) #[2,3,4,none]
self.assertFalse(s1.is_empty()) # this is saying that the statement that the string is empty is false
def test_if_full(self):
s1 = StackArray(3) #[none,none,none]
s1.push(5) #[5,none,none]
s1.push(4) #[5,4,none]
s1.push(3) #[5,4,3]
self.assertTrue(s1.is_full()) #this is checking to see if its true that the stack is full
def test_if_not_full(self):
s1 = StackArray(2) # [none,none]
s1.push(2) # [2,none]
self.assertFalse(s1.is_full()) # it is false that the stack is full
def test_IfWeCanPush(self):
s1 = StackArray(3) #[none,none,none]
s1.push(2) #[2,none]
s1.push(3) #[2,3]
self.assertFalse(s1.is_full()) # it is false that the stack is full
def test_IfWeCantPush(self):
s1 = StackArray(3) #[none,none,none]
s1.push(2) #[2,none,none]
s1.push(3) #[2,3,none]
s1.push(3) #[2,3,3]
self.assertTrue(s1.is_full())
def test_ifWeCanPop(self):
s1 = StackArray(3) #[none,none,none]
s1.push(3) #[3,none,none]
s1.push(3) #[3,3,none]
s1.push(5) #[3,3,5]
# This gives us an array [3,3,5]
s1.pop() # now we have [3,5]
s1.pop() # now we have [5]
self.assertFalse(s1.is_empty())
self.assertEqual(s1.pop(),5)
def test_ifWeCantPop(self):
s1 = StackArray(2) # this gives us [none,none]
self.assertFalse(s1.pop())
def test_ifWeCanPeek(self):
s1 = StackArray(4)
s1.push(4)
s1.push(3)
s1.push(5)
s1.push(54)
self.assertEqual(s1.peek(),4) #this statement says that if we peek at the top of the stack it should be 4
def test_ifWeCanSeeTheSize(self):
s1 = StackArray(5)
s1.push(3)
self.assertEqual(s1.size(),1) # this statement checks that the size or number of items in the
# stack is 1 ... [ 3,none,none,none,none] only has one item which is 3
if (name == 'main'):
unittest.main()
I am trying to solve this problem:
Imagine a (literal) stack of plates. If the stack gets too high, it
might topple. There- fore, in real life, we would likely start a new
stack when the previous stack exceeds some threshold. Implement a data
structure SetOfStacks that mimics this. SetOf- Stacks should be
composed of several stacks, and should create a new stack once the
previous one exceeds capacity. SetOfStacks.push() and
SetOfStacks.pop() should behave identically to a single stack (that
is, pop() should return the same values as it would if there were just
a single stack). Bonus: Implement a function popAt(int index) which
performs a pop operation on a specific sub-stack.
So I wrote the code:
#!/bin/env python
from types import *
class Stack:
def __init__(self):
self.items = []
self.capacity = 3
self.stackscount = 0
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
# How to create a new instance of Stack class at runtime ?
# the __init__ must be run too.
def push(self, item):
if self.size() <= self.capacity:
self.items.append(item)
else:
self.create()
def pop(self):
return self.items.pop()
def popAt(self):
pass
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s = Stack()
s.push(10)
How do I create a new s type object dynamically at runtime? I searched on the internet and found that using new.instance or new.classobj is the solution but when I did so my new object did not seem to have items from __init__ function. In python3, type() seems to be the answer but the docs doesn't have any examples.
You've confused yourself by referring to a "type object". In Python that means the class itself, not its instances.
To create new Stack objects, simply do what you're already doing: call the Stack class. You can append them to a list:
stacks = [Stack() for _ in range(5)]
However, as jon points out, that won't solve your problem since you haven't defined the SetOfStacks class.
You could simply use a parent-child relation : when a Stack is full, it creates a child and delegate next pushes to it. It could lead to :
class Stack:
def __init__(self, parent = None, id=None):
self.stackscount = 0
self.capacity = 3
self.items = []
self.parent = parent
self.id = id
self.child = None
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
return Stack(self, id)
def push(self, item):
if self.size() <= self.capacity:
self.items.append(item)
else:
if self.child is None:
self.child = self.create()
self.child.push(item)
def pop(self):
if self.child is not None:
item = self.child.pop()
if len(self.child.items) == 0:
self.child = None
else:
item = self.items.pop()
return item
def popAt(self):
pass
def peek(self):
if self.child is not None:
item = self.child.peek()
else:
item = self.items[len(self.items)-1]
return item
def size(self):
l = len(self.items)
if self.child is not None:
l += self.child.size()
return l
s = Stack()
s.push(10)
popAt is still to be implemented, but I tested it and it correctly creates new stacks when pushing and empties and removes them when popping.
The implementation of popAt will require some evolutions to current pop implementation, to allow removing an intermediate stack :
def pop(self):
if self.child is not None:
item = self.child.pop()
if len(self.child.items) == 0:
self.child = self.child.child
if self.child is not None:
self.child.parent = self
else:
item = self.items.pop()
return item
def popAt(self, stacknumber):
s = self
for i in range(stacknumber):
s = s.child
if s is None:
return None
if len(s.items) == 0:
return None
item = s.items.pop()
if len(s.items) == 0 and s.parent is not None:
s.parent.child = s.child
if s.child is not None:
s.child.parent = s.parent
return item
The type() function is indeed what you are looking for. Documentation can be found here: https://docs.python.org/2/library/functions.html#type
You can call it like this:
# Bases is a tuple of parent classes to inherit
bases = Stack,
# Dict contains extra properties for the class, for example if you want to add a class variable or function
dict_ = {}
# Construct the class
YourClass = type('YourClass', bases, dict_)
# Create an instance of the class
your_instance = YourClass()
It looks like you are just looking at instance creation though:
class Stack(object):
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
# How to create a new instance of Stack class at runtime ?
# the __init__ must be run too.
stack = Stack()
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")