Functions & Scope · Question 18 · Hard

The recursive function below counts how many moves a number needs to reach 1 (halve if even, otherwise 3n + 1). What is printed for 6?

def steps(n):
    if n == 1:
        return 0
    if n % 2 == 0:
        return 1 + steps(n // 2)
    return 1 + steps(3 * n + 1)

print(steps(6))
  1. 7
  2. 9
  3. 6
  4. 8
Answer and explanation

Answer: D. 8

Explanation: The chain is 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1. That is 8 moves, and each recursive call adds 1 for one move.

Previous: A default parameter value refers to a module-level variable that is changed… · Next: Which statement about the nonlocal keyword in Python is correct?

Practise functions & scope

Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.

More functions & scope questions

More python practice

Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge