Question:

Write the following user-defined functions in Python:

(i) push_trail(N, myStack): Here N and myStack are lists, and myStack represents a stack.
The function should push the last 5 elements from the list N onto the stack myStack.
Assume that N contains at least 5 elements.

(ii) pop_one(myStack): The function should pop an element from the stack myStack, and return this element.
If the stack is empty, then the function should display the message 'Stack Underflow', and return None.

(iii) display_all(myStack): The function should display all the elements of the stack myStack, without deleting them.
If the stack is empty, the function should display the message 'Empty Stack'.

Show Hint

Use N[-5:] to get the last 5 elements.
Always check stack length before popping to avoid errors.
Printing a stack doesn’t delete its contents unless pop() is used.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

(i) push_trail():

def push_trail(N, myStack):
    last_five = N[-5:]
    for item in last_five:
        myStack.append(item)
    print("Last 5 elements pushed onto the stack.")
This function slices the last 5 elements from list N using N[-5:].
It then appends each of these elements to myStack,
which represents the stack structure.
A message is printed to confirm the operation.

(ii) pop_one():

def pop_one(myStack):
    if len(myStack) == 0:
        print("Stack Underflow")
        return None
    else:
        return myStack.pop()
This function first checks whether myStack is empty.
If it is, it prints 'Stack Underflow' and returns None.
Otherwise, it removes and returns the top element using pop().

(iii) display_all():

def display_all(myStack):
    if len(myStack) == 0:
        print("Empty Stack")
    else:
        for item in myStack:
            print(item, end=" ")
        print()
This function prints all items in myStack without modifying the stack.
If the stack is empty, it prints 'Empty Stack'.
Otherwise, it prints each item with a space.
Was this answer helpful?
0
0

Top Questions on Programming in Python

View More Questions