I can only push two values onto the stack array? - python

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.

Related

I did define but why asking checkBrackets not defined

I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.---> 50 result = checkBrackets(equation)
I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
statck.push(ch)
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flg, size)
equation = input ("Enter_qauation: ")
result = checkBrackets(equation)
print ("%s_%d"%(result[0],result[1]))
The function is defined, but it is defined in the class Stack so you need to call it as Stack.checkBrackets(equation). There were two more errors(spelling errors), so the final code looks like:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
stack.push(ch) # spelling correction
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flag, size) # spelling correction
equation = input ("Enter_equation: ")
result = Stack.checkBrackets(equation) # Changed Line
print ("%s_%d"%(result[0],result[1]))
Sample Output 1:
Enter_qauation:
(1+2)=3
OK_2
Sample Output 2:
Enter_qauation:
1+2=(3
Wrong_1

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))

LinkedQueues and simulated printer

I am aware that there is another post asking about simulated printers but I didn't find any actual answers to my own question there.
class LinkedQueue :
class _Node :
__slots__ = '_element', '_next'
def __init__(self, element, next = None):
self._element = element
self._next = next
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def __len__(self) :
return self._size
def is_empty(self) :
return self._size == 0
def first(self) :
if self.is_empty() :
raise Empty('Queue is empty')
return self._head._element
def dequeue(self) :
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty() :
self._tail = None
return answer
def enqueue(self, e) :
newest = self._Node(e,None)
if self.is_empty() :
self._head = newest
else :
self._tail._next = newest
self._tail = newest
self._size += 1
class Printer:
def __init__(self, name, job_queue):
self._name = name
self._job_queue
self._current_job = None
class Empty(Exception) :
pass
def main():
p_jobs = LinkedQueue()
red = Printer("Red", p_jobs) # Creates Printer Red
green = Printer("Green", p_jobs) # Creates Printer Green
print("\nOptions:\n 1. Add Job \n 2. Print Pages \n 3. Status \
\n 4. Quit")
i = 0
while True:
n = str(input("\nChoice (Type the number): "))
if n == '1': # Add Job
i += 1
p = int(input("\nHow many pages? "))
j = p_jobs.job_list(i,p,next)
p_jobs.enqueue(j)
if n == '2': # Print Job
print()
p_jobs.dequeue()
i -= 1
if n == '3': # Status
print()
if n == '4': # Quit
print("\nGoodbye!")
break
This is the provided code for us. We are supposed to simulate two printers that print out pages from jobs using LinkedQueue and Node.
I have the main function barebones w/c consists of 4 options:
Add Job, Print Jobs, Status, and Quit
I have trouble understanding how to use (refer) to the enqueue and dequeue methods. Can somebody break down each part of this program so I can at least understand where to start. I also would appreciate any hints that tell me where to go from here. Thank you.
EDIT: I added my main function w/c is basically just a UI
While this is by no means a complete answer, it shows how to print out what's currently in a LinkedQueue instance.
First, add the following method to the class. It will allow the contents to be iterated.
class LinkedQueue:
def __iter__(self):
if self.is_empty():
return None # No jobs in print queue.
cur = self._head
while cur:
yield cur._element
cur = cur._next
Here's something demonstrating how to use it:
def test():
q = LinkedQueue() # Create a queue.
# Add some jobs to the LinkedQueue.
for j in range(3):
pages = randint(1, 10)
q.enqueue(('job #{}'.format(j), pages))
# Show what's currently in the LinkedQueue.
for v in q:
print(v)
# Modify the LinkedQueue and then show what's left in it.
j = q.dequeue()
print('\nafter removing one job')
for v in q:
print(v)

AttributeError: 'str' object has no attribute 'insert'

I'm trying to insert a piece of text into my linked list. However, when ever I try to do this I get an error "AttributeError: 'str' object has no attribute 'insert'". I am writing this in python 3.3.
class Node:
def __init__(self, item= None , link= None ):
self.item = item
self.next = link
def __str__(self):
return str(self.item)
class List:
def __init__(self):
self.head = None
self.count = 0
def is_empty(self):
return self.count == 0
def is_full(self):
return False
def reset(self):
self.__init__()
def __len__(self):
return self.count
def _getNode(self, index):
node = self.head
for _ in range(index):
node = node.next
return node
def insert(self, index, item):
if index < 0:
index = 0
elif index > len(self):
index = len(self)
if index == 0:
self.head = Node(item, self.head)
else:
node = self._getNode(index - 1)
node.next = Node(item, node.next)
self.count += 1
def delete(self, index):
if self.is_empty():
raise IndexError("List is empty")
if index < 0 or index >= len(self):
raise IndexError("Index is out of range")
if index == 0:
self.head = self.head.next
else:
node = self._getNode(index - 1)
node.next = node.next.next
self.count -= 1
import LinkedList
text= LinkedList.List()
def insert_num(line,text):
text.insert(line - 1,text)
def delete_num(line):
if line is None:
text.reset
else:
text.delete(line)
def print_num(line):
if line is None:
i= 0
while i< line.count:
item= text._getNode(i)
print (item)
else:
print(text._getNode(line))
while True:
print("1. Insert")
print("2. Delete")
print("3. Print")
print("4. Quit")
command = int(input())
if command == 1:
line = int(input("At what line do you wish to insert your text?: "))
text = input("Text: ")
insert_num(line,text)
elif command == 2:
line = int(input("What line do you wish to delete?: "))
delete_num(line)
elif command == 3:
line = int(input("What line do you wish to print?: "))
elif command == 4:
break
else:
print("invalid input, please select one of the following numbers:")
In your main loop, you call insert_num(line, text). But text here is the text string you inputted above, not the global variable text which is an instance of your LinkedList class. As the error says, strings don't have an insert method (because they are immutable).
You call these two lines
text = input("Text: ")
insert_num(line,text)
The resulting text variable will be type str, not a linked list. Strings do not have an insert, as the error is telling you.
And when you call these two lines:
import LinkedList
text= LinkedList.List()
That is a different text variable than the one that exists within the scope of your insert_num function.
The problem is variable scoping. When you call your insert_num() procedure you want to insert your new line (the text parameter, which is of type str) into your LinkedList of lines, which is also called text but because the method has a parameter with the same name, this (the linked list) is outside of the scope, and so can't be seen by the procedure.
text= LinkedList.List()
def insert_num(line,text):
text.insert(line - 1,text)
I'd rename the subroutine's parameter:
text= LinkedList.List()
def insert_num(line_number, new_line):
text.insert(line_number - 1,new_line)
.insert() Method can be used with list only, but you are trying to use it with a string. That is why you are getting error

Stack data structure in 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")

Categories

Resources