Count the steps, with a limit
Beginner · Write the code · from Undecidable Problems: Questions No Program Can Always Answer
From the lesson: Undecidable Problems: Questions No Program Can Always Answer
Some yes-or-no questions can be answered by a program for every possible input, and some cannot be answered by any program at all, no matter how fast the computer or how clever the programmer.
Read the lessonWrite steps_to_one(n, limit) for the halve-or-triple rule: while n is not 1, an even n becomes n // 2 and an odd n becomes 3 * n + 1.
Return the number of steps it took to reach 1. If it has not reached 1 after limit steps, return None instead: your program gives up on that instance rather than running forever.
def steps_to_one(n, limit):
# Your code here
pass
What Check runs
Your code runs first, then each of these lines, and 1 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| steps_to_one(6, 100) | 8 |
| steps_to_one(1, 100) | 0 |
| print(steps_to_one(27, 50)) | None |
More Undecidable Problems exercises
- Does the counting loop stop?Intermediate