In: Computer Science
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?
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.