OA. free
Free
Warner Bros Data Structures & Algorithms Core Computer Science Medium

What is the output of the following Python program?

Warner Bros technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What is the output of the following Python program?

def print_pattern(left, right):
    if right >= left:
        return
    text = "{0} {1},"
    if left - right > 0 and left - right >= right:
        print(text.format(right, left - right), end=" ")
        print_pattern(left, right + 1)

print_pattern(8, 1)
Choose one option.
Show answer & explanation
Answer: B. 1 7, 2 6, 3 5, 4 4,

The recursive calls print pairs as long as left - right is at least right. This succeeds for right = 1, 2, 3, and 4, then stops at right = 5, so the final pair is printed only once.

Step-by-step Derivation:
Step 1: print_pattern(8, 1) -> 8 - 1 = 7, and 7 >= 1 is true, so print "1 7, " and recurse with right = 2.
Step 2: print_pattern(8, 2) -> 8 - 2 = 6, and 6 >= 2 is true, so print "2 6, " and recurse with right = 3.
Step 3: print_pattern(8, 3) -> 8 - 3 = 5, and 5 >= 3 is true, so print "3 5, " and recurse with right = 4.
Step 4: print_pattern(8, 4) -> 8 - 4 = 4, and 4 >= 4 is true, so print "4 4, " and recurse with right = 5.
Step 5: print_pattern(8, 5) -> 8 - 5 = 3, and 3 >= 5 is false, so nothing is printed and the recursion stops.
Final output: 1 7, 2 6, 3 5, 4 4,