Question

In: Computer Science

import Stack def stack_mystery(myStack):      mystery=0     while not myStack.isEmpty():          value=myStack.pop()          if v

import Stack

def stack_mystery(myStack):

     mystery=0

    while not myStack.isEmpty():

         value=myStack.pop()

         if value> mystery:

             mystery=value

       

       return mystery

def main():

   s=Stack.Stack()

       s.push(20)

       s.push(10)

       s.push(50)

       s.push(100)

       s.push(40)

       print(stack_mystery(s))

main()

Answer the following questions

a) What is the output of the print(stack_mystery(s)) statement in the main method?

b) What is the task of the stack_mystery function? What does the mystery variable represent?

Solutions

Expert Solution

Here is the solution,

a) The output of the code is 100

b) Explaination of the function stack_mystery()

The stack_mystery() is having the parameter in form of a object which belongs to a class Stack (which basically performs the stack operations.

Inside stack_mystery there is a local variable named "mystery" which has initial value 0.

The while basically runs till the point the stack is not empty.

inside the loop, for the first iteration the value that gets poped is 40 (since that was the last element pushed)

This value(40) gets compared with mystery, since value > mystery, mystery gets the value 40 (inside if satement)

Now the new value of mystery is 40

For second iteration the stack pops the value i.e 100.

again this value of 100 gets compared with mystery(which is 40). The if statement becomes true because

value > mystery and so mystery gets the new value 100.

Now for every other iterations, the if statement, the conditions goes false as the value of mystery is greater than rest of the poped values (i.e 50,10,20)

Finally the function returns the value of mystery which is 100 (gets printed on console)

For better understanding i have developed the class program so that you can use the code and check the output:-

please keep the class program and the main program in the same folder.

#your code starts here
class Stack:
def __init__(self):
self.L=[]

def push(self,x):
self.L.append(x)

def pop(self):
if not self.isEmpty():
return self.L.pop()
  
def isEmpty(self):
if self.L != []:
return False
else:
return True
# code ends here

#your code starts here
import Stack
def stack_mystery(myStack):
mystery=0
while not myStack.isEmpty():
value = myStack.pop()
if value > mystery:
mystery = value
return mystery
def main():
s=Stack.Stack()
s.push(20)
s.push(10)
s.push(50)
s.push(100)
s.push(40)

print(stack_mystery(s))
main()
# code ends here

output:- 100

here is the screenshot of the code:-

Thank you.


Related Solutions

from MyStack import MyStack def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"]...
from MyStack import MyStack def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"] = 2    prec["-"] = 2    prec["("] = 1    opStack = Stack()    postfixList = []    tokenList = infixexpr.split()    for token in tokenList:        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":            postfixList.append(token)        elif token in prec:        op_2=operand_stack.peek()        operand_stack.pop()        op_1=operand_stack.peek()        operand_stack.pop()        operand_stack.push("("+op_1+token+op_2+")")    temporary_list.append(operand_stack.pop())    for i in temporary_list[0]:        infix_list.append(i)    return " ".join(infix_list) print(postfix_to_infix("3 6 7*+")) def doMath(op, op1, op2):   if op == "*":       return op1 * op2   elif...
def mystery(L, x): if L==[]: return False if L[0] == x: return True L.pop(0) return mystery(L,...
def mystery(L, x): if L==[]: return False if L[0] == x: return True L.pop(0) return mystery(L, x) What is the input or length size of the function mystery? What is the final output of mystery([1,3,5,7], 0)? Explain in one sentence what mystery does? What is the smallest input that mystery can have? Does the recursive call have smaller inputs? Why? Assuming the recursive call in mystery is correct, use this assumption to explain in a few sentences why mystery is...
#include <iostream> #include <stack> #include <queue> using namespace std; void printFromStack(string expr){ stack<char> myStack; for(int i=0;...
#include <iostream> #include <stack> #include <queue> using namespace std; void printFromStack(string expr){ stack<char> myStack; for(int i=0; i<expr.length(); i++){ //Insert code here to push each character onto the stack } cout << "My stack is popped in this order" << endl; while(!myStack.empty()){ //Insert code here to cout the top of the stack one by one //Pop each one after it’s printed out } cout << endl; } void printFromQueue(string expr){ queue<char> myQueue; //Insert code here to push each character onto the...
Implement a generic MyStack class using templates. A stack allows elements to be added and removed...
Implement a generic MyStack class using templates. A stack allows elements to be added and removed in a last-in, first-out (LIFO) manner. Stacks have an operation called push to place elements at the top of the stack, and another operation called pop to remove and return the element at the top of the stack. The only element on the stack that may be referenced is the one on the top. This means that if two elements are pushed onto the...
Mystery(y, z: positive integer) 1 x=0 2 while z > 0 3       if z mod 2...
Mystery(y, z: positive integer) 1 x=0 2 while z > 0 3       if z mod 2 ==1 then 4                x = x + y 5       y = 2y 6       z = floor(z/2)           //floor is the rounding down operation 7 return x Simulate this algorithm for y=4 and z=7 and answer the following questions: (3 points) At the end of the first execution of the while loop, x=_____, y=______ and z=_______. (3 points) At the end of the second execution of...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top = -1 #the index of the top element of the stack. -1: empty stack self.data = [] def push(self, item): # add item to the top of the stack. O(1) self.top += 1 self.data.append(item) def pop(self): # removes and returns the item at the top O(1) self.top -=1 return self.data.pop() def peek(self): # returns the item at the top O(1) return self.data[len(self.data)-1] def isEmpty(self):...
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits = '0b' + bits     value = int(bits, 2)     return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode() def writeMessageToRedChannel(file, message):     image = Image.open(file)     width, height = image.size     messageBits = stringToBits(message)     messageBitCounter = 0     y = 0     while y < height:         x = 0         while x < width:             r, g, b, a = image.getpixel((x, y))             print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)"...
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2...
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2 topBound = win.window_height() / 2 bottomBound = -win.window_height() / 2 turtleX = turt.xcor() turtleY = turt.ycor() stillIn = True if turtleX > rightBound or turtleX < leftBound: stillIn = False if turtleY > topBound or turtleY < bottomBound: stillIn = False return stillIn def main(): wn = turtle.Screen() # Define your turtles here june = turtle.Turtle() june.shape('turtle') while isInScreen(wn,june): coin = random.randrange(0, 2) if...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and stillOK: pos2 = 0 found = False while pos2 < len(alist) and not found: if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None else: stillOK = False pos1 = pos1 + 1 return stillOK include all operations and calculate the Big-O and the values for c and n0.
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0,...
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0, 0, 0], [-math.sin(math.pi/6), 0, -math.sin(math.pi/3), 0, 0, 0], [math.cos(math.pi/6), 1, 0, 1, 0, 0], [math.sin(math.pi/6), 0, 0, 0, 1, 0], [0, -1, -math.cos(math.pi/3), 0, 0, 0], [0, 0, math.sin(math.pi/3), 0, 0, 1]]) b = np.array([0, 2000, 0, 0, 0, 0]) x = [0, 0, 0, 0, 0, 0] def seidel(a, x, b): # Finding length of a(3) n = len(a) # for loop for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT