CBSE Class 12 Computer Science Question 43 of 63

Data Structures in Python — Question 17

Back to all questions
17
Question

Question 17

A Stack STK and Queue QUE is being maintained. Their maximum size is the same:

(i) check whether they have the same size, i.e., have the same number of elements.

(ii) check for equality of Stack and Queue, i.e.,

  1. Retrieve an element from the Stack and one element from the Queue.
  2. Compare the two.
  3. Stop and report if elements are different.
Solution
def is_empty(stack_or_queue):
    return len(stack_or_queue) == 0

def size(stack_or_queue):
    return len(stack_or_queue)

def check_size_equality(stack, queue):
    return size(stack) == size(queue)

def check_element_equality(stack, queue):
    if check_size_equality(stack, queue) == False:
        print("The size of stack and Queue is not equal.")
        return False
    
    while not is_empty(stack) and not is_empty(queue):
        stack_element = stack.pop()
        queue_element = queue.pop(0)

        if stack_element != queue_element:
            return False

    return True

STK = [1, 2, 3]
QUE = [3, 2, 1]

print("Size Equality Check:", check_size_equality(STK, QUE))

print("Element Equality Check:", check_element_equality(STK, QUE))
Output
Size Equality Check: True
Element Equality Check: True
Answer