Looking at the letter of the problem, it does not seem the user does not need to map 0
to anything unless is preceded by a 1
, in which case it will be mapped to ten
. I don't know if that is a mispecification of the problem or a genuine need. In the first case, solutions above address the objective pretty well.
Otherwise, we could take the following approach:
table = {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten"
}
def digits_to_letters(s, default= "-"):
s = list(s)[::-1]
res = []
while len(s) > 0:
l1 = s.pop()
n1 = int(l1)
c1 = table.get(n1, " ")
if (n1 == 1) and (len(s) > 0):
l2 = s.pop()
n1n2 = int(l1 + l2)
c1c2 = table.get(n1n2)
if c1c2:
res.append(c1c2)
else:
res.append(c1)
res.append(table.get(int(l2), default))
else:
res.append(c1)
return res
print(digits_to_letters("123102303231"))
OUTPUT
['one', 'two', 'three', 'ten', 'two', 'three', ' ', 'three', 'two', 'three', 'one']
As you can see, the forth and fifth characters - 10
- are mapped to ten
, while the seventh and eighth - 30
- to three
and
(there is the option to choose a different default character instead of an empty space).