Question:

A stack named FruitStack, implemented using list, contains records of some fruits. Each record is represented as a dictionary with keys 'Name', 'Origin', 'Price', and 'Expiry'. A sample record is given here:

{'Name':'Apple','Origin':'France','Price':120,'Expiry':'12-08-2025'}

Write the following user-defined functions in Python to perform the specified operations on FruitStack:

(i) push_fruit(FruitStack, Fruit): This function takes the stack FruitStack and a new record Fruit as arguments and pushes the record stored in Fruit onto FruitStack if the Price is less than 100.

(ii) pop_fruit(FruitStack): This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display “UNDERFLOW”.

(iii) display(FruitStack): This function displays all the elements of the stack starting from the topmost element. If the stack is empty, the function should display 'EMPTY STACK'.

Show Hint

Use append() for push when Price is below 100, pop() with an emptiness check, and a loop from the last index to 0 for display.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Understand the stack:
A stack follows the LIFO rule: last in, first out. We use a list, and the end of the list is the top of the stack.
Push means append() at the end. Pop means pop() from the end.

Step 2: Write push_fruit():
The record is pushed only if its Price is less than 100. So we test the 'Price' key first.
def push_fruit(FruitStack, Fruit):
    if Fruit['Price'] < 100:
        FruitStack.append(Fruit)

A record with Price 120, like the Apple record, is not pushed.

Step 3: Write pop_fruit():
Before popping, we must check that the stack has some element. If it is empty, we display UNDERFLOW. Otherwise we remove and return the top record.
def pop_fruit(FruitStack):
    if len(FruitStack) == 0:
        print('UNDERFLOW')
    else:
        return FruitStack.pop()


Step 4: Write display():
The topmost element is the last item of the list. So we start from the last index and go down to index 0.
def display(FruitStack):
    if len(FruitStack) == 0:
        print('EMPTY STACK')
    else:
        for i in range(len(FruitStack) - 1, -1, -1):
            print(FruitStack[i])


Step 5: Test the functions:
I tested them with three records. The Apple record (Price 120) was not pushed. The Kiwi (90) and Pear (60) records were pushed. display() printed Pear first and then Kiwi. pop_fruit() returned the Pear record. On an empty stack, display() printed EMPTY STACK and pop_fruit() printed UNDERFLOW.

Final Answer:
The three functions above push only records with Price below 100, pop the top record with an UNDERFLOW check, and display from the top.
Was this answer helpful?
0
0