Repository navigation
collatz_countdown: why does s==1 return 1 instead of 0? #21
|
def collatz_countdown(s):
if s == 1 :
return 1
elif s < 1:
print ("invalid value cannot collatz values less than 1")
return None
i = 0
while s > 1:
if s % 2 == 0:
s = s / 2
else:
s = (3 * s) + 1
i += 1
return i
print(collatz_countdown(12))For |
Replies: 1 comment
|
It reads as an off-by-one bug, not a deliberate alternative convention — and the loop's own invariant proves it. Walk the loop's contract: Now apply the same contract to the already-terminal case: if s == 1:
return 0Returning Two adjacent notes while you're in the file:
Nice question to ask about your own answer file — this is exactly the kind of edge-case discipline the piscine drills are for. |
It reads as an off-by-one bug, not a deliberate alternative convention — and the loop's own invariant proves it.
Walk the loop's contract:
icounts transitions — each iteration applies one Collatz step (s → s/2ors → 3s+1) and incrementsionce. When the loop exits,shas become 1, andiis the number of steps taken to get there.collatz_countdown(12)returns 9:12→6→3→10→5→16→8→4→2→1is nine transitions. ✓Now apply the same contract to the already-terminal case:
collatz_countdown(1)— how many steps does it take for 1 to be at 1? Zero. There are no transitions, so by the function's own semantics the answer is0, and the early-exit branch should read:Returning
1…