Question:

A stack, named ClrStack, contains records of some colors. Each record is represented as a tuple containing four elements — ColorName, RED, GREEN, BLUE. ColorName is a string, and RED, GREEN, BLUE are integers. For example, a record in the stack may be ('Yellow', 237, 250, 68).

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

(i) push_Clr(ClrStack, new_Clr): This function takes the stack ClrStack and a new record new_Clr as arguments and pushes this new record onto the stack.

(ii) pop_Clr(ClrStack): This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display the message "Underflow".

(iii) isEmpty(ClrStack): This function checks whether the stack is empty. If the stack is empty, the function should return True, otherwise the function should return False.

Show Hint

Use append() to push, pop() to remove the top element,
and always check length before popping to avoid errors.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

(i) push_Clr():

def push_Clr(ClrStack, new_Clr):
    ClrStack.append(new_Clr)
    print("New color record pushed to stack.")
This function uses the append() method
to add the new record new_Clr to the end of the stack ClrStack.
A confirmation message is displayed for clarity.

(ii) pop_Clr():

def pop_Clr(ClrStack):
    if len(ClrStack) == 0:
        print("Underflow")
        return None
    else:
        return ClrStack.pop()
This function first checks if ClrStack is empty
by checking if its length is zero.
If empty, it prints "Underflow" and returns None.
Otherwise, it pops and returns the topmost record.

(iii) isEmpty():

def isEmpty(ClrStack):
    if len(ClrStack) == 0:
        return True
    else:
        return False
This function checks if the length of ClrStack is zero.
If it is zero, it returns True to indicate the stack is empty.
Otherwise, it returns False.
Was this answer helpful?
0
0

Top Questions on Programming in Python

View More Questions