Recursion

Collatz Conjecture
Collatz Conjecture in Python
def steps(number):
    if number <= 0:
        raise ValueError("Only positive integers are allowed")
    if number == 1:
        return 0
    number = number / 2 if number % 2 == 0 else number * 3 + 1
    return 1 + steps(number)

This approach uses recursion to solve the challenge. Recursion is less common as a strategy in Python than in other "fully-functional" programming languages such as Elixir, Haskell, and Clojure. While it can be powerful, it can also be trickier to implement than looping constructs.

This approach starts with checking if number <= 0 and raising a ValueError if it is. Next, we return zero if number == 1. This is the base case.

We then assign number to the same conditional expression as seen in the ternary operator approach. Finally, we return one plus the result of calling steps(), with the updated number value. This is the recursive case.

Solving this exercise in this way removes the need for a counter variable and the creation of a loop. If number is not equal to one, we call 1 + steps(number). Then steps() can execute the same code again with new values. This makes a long chain (or stack) of 1 + steps(number) — until number == 1 and the code adds zero and exits. That translates to something like: 1 + 1 + 1 + 1 + 0.

Python doesn't have tail call optimization, so the stack of 1 + steps(number) will continue to grow until the base case triggers resolution, or the code reaches the recursion limit.

Caution

In Python, we can't have a function call itself more than 1000 times by default. Code that exceeds this recursion limit will throw a RecursionError.

While it is possible to adjust the recursion limit, doing so risks crashing Python and may also crash your system with a stack overflow. Casually raising the limit is not recommended and seldom helps the performance situation. Instead, applying memoization techniques or dynamic programming strategies is a better path.

12th Aug 2026 · Found it useful?