Predict the output
What does this print?
def readings(s: str) -> int:
if not s:
return 1
total = 0
if s[0] != "0":
total += readings(s[1:])
if len(s) > 1 and 10 <= int(s[:2]) <= 26:
total += readings(s[2:])
return total
print(readings("226"), readings("106"), readings("30"))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3 1 0
Right: 2-2-6, 22-6 and 2-26; only 10-6; and '30' has no reading.
The plain recursion repeats suffixes; caching by position turns it into the O(n) table.
Why not the others?
- B 3 2 1. '0' cannot stand alone, so '1-0-6' and '3-0' fail.
- C 2 1 0. '226' also reads as 2-26.