Stack Questions
Stack Questions
Each record is represented as a list containing name of the student and marks. The
keys are the roll numbers.
Write the following user-defined functions in Python to perform the
specified operations on the dictionary:
(I) push(d): This function takes the dictionary as an argument and pushes the names
and marks onto the stack whose marks is greater than equal to 95.
(II) pop(): This function pops the topmost book record
from the stack and returns it. If the stack is already empty, the
function should display "stack empty".
(III) peep(): This function displays the topmost element of
the stack without deleting it. If the stack is empty, the function
should display 'None'.
Solution:
d={1:["Abc",95],2:["XYZ",85],3:["PQR",98]}
stk=[]
def push(d):
for i in d:
if d[i][1]>=95:
stk.append(d[i])
print(stk)
def peek():
if stk==[]:
print("None")
else:
print(stk[-1])
def pop():
if stk==[]:
print("Stack is empty")
else:
stk.pop()
print(stk)
push(d)
peek()
pop()
Solution:
N=[1,2,3,4,5,6,7,8]
EvenNumbers = []
def push_even(N):
for num in N:
if num % 2 == 0:
EvenNumbers.append(num)
print(EvenNumbers)
def pop_even():
if EvenNumbers==[]:
print("Stack is empty")
else:
EvenNumbers.pop()
def display_even():
if EvenNumbers==[]:
print("None")
else:
print(EvenNumbers)
push_even(N)
pop_even()
display_even()
Solution:
def pop_book(BooksStack):
if BooksStack==[]:
print("Underflow")
else:
return(BooksStack.pop())
def peep(BooksStack):
if BooksStack==[]:
print("None")
else:
print(BooksStack[-1])
push_book(BooksStack, new_book)
pop_book(BooksStack)
peep(BooksStack)