Reverse and Add
Advanced · Stretch · from Python While Loops: When For Loops Aren't Enough
From the lesson: Python While Loops: When For Loops Aren't Enough
A vending machine doesn't know how many coins you'll insert. It just keeps waiting: "while the total is less than the price, keep accepting coins." It can't use a for loop because it doesn't know the number of iterations in advance. It needs a while loop.
Read the lessonTake a number, add it to its own reverse, and repeat until the result reads the same forwards and backwards (a palindrome):
87 + 78 = 165
165 + 561 = 726
726 + 627 = 1353
1353 + 3531 = 4884 (a palindrome after 4 additions)Write a function steps_to_palindrome(n) that returns how many additions it takes. A number that is already a palindrome needs 0. Some numbers never seem to get there, so give up after 30 additions and return -1.
steps_to_palindrome(87) # 4
steps_to_palindrome(56) # 1 (56 + 65 = 121)Return the answer instead of printing it: Check calls steps_to_palindrome() with its own numbers, some of them hidden.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| steps_to_palindrome(87) | 4 |
| steps_to_palindrome(56) | 1 |
More While Loop exercises
- Countdown TimerBeginner
- Power of 2 FinderBeginner
- Predict the OutputBeginner
- Fix the Bug: Digit CounterBeginner
- The Collatz SequenceBeginner
All Python exercises · 50 practice problems · Control Flow quiz