There are various approaches to solving the Collatz Conjecture exercise in Python. You can for example use a while loop or a recursive function. You can also solve it by using if and else statements or the ternary operator.
The key to this exercise is to check if the number and then do the correct operation. Under this process you are supposed to count how many steps it takes to get to one.
This is a good way to solve the exercise, it is easy to understand and it is very readable. The reason why you might not want to use this approach is because it is longer than the other approaches.
def steps(number):
if number <= 0:
raise ValueError("Only positive integers are allowed")
counter = 0
while number != 1:
if number % 2 == 0:
number /= 2
else:
number = number * 3 + 1
counter += 1
return counter
For more information, check the if/else approach.
In this approach we replace the if/else
multi-line construction with a conditional expression, sometimes called a ternary operator.
This syntax allows us to write a one-line if/ else
check, making the code more concise.
def steps(number):
if number <= 0:
raise ValueError("Only positive integers are allowed")
counter = 0
while number != 1:
number = number / 2 if number % 2 == 0 else number * 3 + 1
counter += 1
return counter
For more information, check the Ternary operator approach.
In this approach we use a recursive function. A recursive function is a function that calls itself. This approach can be more concise than other approaches, and may also be more readable for some audiences.
The reason why you might not want to use this approach is that Python has a recursion limit with a default of 1000.
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)
For more information, check the Recursion approach.
To get a better understanding of the performance of the different approaches, we have created benchmarks. For more information, check the Performance article.