OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

What is the expected output of the following Python program?

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

What is the expected output of the following Python program?

List = [3.1416, 1.618, 2.7183, 0.57721]
func = lambda x: (func(x[1:]) + x[:1]) if x else []
print(func(List))
Choose one option.
Show answer & explanation
Answer: A. [0.57721, 2.7183, 1.618, 3.1416]

The lambda function recursively reverses the list by taking the rest of the list (x[1:]), recursing on it, and appending the first element (x[:1]) to the end. Lambda functions can call themselves via variable reference. The recursion unwinds from the empty base case, building the reversed list from the last element backward.

Step-by-step Derivation:
Execution trace:

  1. func([3.1416, 1.618, 2.7183, 0.57721])
  2. → func([1.618, 2.7183, 0.57721]) + [3.1416]
  3. → (func([2.7183, 0.57721]) + [1.618]) + [3.1416]
  4. → ((func([0.57721]) + [2.7183]) + [1.618]) + [3.1416]
  5. → (((func([]) + [0.57721]) + [2.7183]) + [1.618]) + [3.1416]
  6. → ((([] + [0.57721]) + [2.7183]) + [1.618]) + [3.1416]
  7. → [[0.57721] + [2.7183] + [1.618] + [3.1416]]
  8. → [0.57721, 2.7183, 1.618, 3.1416]

Note: Lambda functions can reference themselves via their assigned variable name, so recursion is supported.