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...
#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)"...
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.
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path): """ Retrieve list of students and their expected grade from file, generate a sampled test grade for each student drawn from a Gaussian distribution defined by the student expected grade as mean, and the given standard deviation. If the sample is higher than 100, re-sample. If the sample is lower than 0 or 5 standard deviations below mean, re-sample Write the list of student...
package SOLUTION; import java.util.Collection; import java.util.Set; public interface MapInterface<K, V> {       /**    *...
package SOLUTION; import java.util.Collection; import java.util.Set; public interface MapInterface<K, V> {       /**    * If the given key is not already in the map, adds the    * key-value pair to the map. Otherwise, updates the old    * value of the existing key to the specified value.    * @param key the key    * @param value the value to be stored in the map with the key    * @return null if the key was not...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT