43. Collatz steps
Start with a whole number and keep applying one rule:
- if the number is even, halve it;
- if it is odd, multiply it by 3 and add 1.
Every number anyone has tried ends up at 1 sooner or later (nobody has proved that all of them do). Starting from 6, the numbers go 6, 3, 10, 5, 16, 8, 4, 2, 1: that's 8 steps.
Write a function collatz_steps(n) that takes a whole number n and returns how many steps it takes to reach 1. A
step is one use of the rule, so n = 1 takes 0 steps.
Example 1
n = 68Example 2
n = 10Example 3
n = 716Constraints
nis a whole number from 1 to 10,000.
Submit also runs 6 more tests you can't see.
Practises While Loops (lesson 14).
- You can't know in advance how many steps there will be, so a
whileloop fits:while n != 1:. - Inside the loop,
n % 2 == 0tells you whethernis even. Usen // 2, which keeps a whole number, for the even case and3 * n + 1for the odd. - Count steps, not numbers: add one each time the rule is applied. For 6 that's 8, though the list 6, 3, ..., 1 has 9 numbers.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def collatz_steps(n):
"""Count the steps from n down to 1.
n: int, 1 or more
Returns: int, how many times the rule is applied
before n becomes 1
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.