integer to english words
return a list with 0 or 1 items
slicing to prevent list index out of range
Stefan Pochmann's solution:
1def numberToWords(self, num):
2 to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \
3 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
4 tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
5 def words(n):
6 if n < 20:
7 return to19[n-1:n]
8 if n < 100:
9 return [tens[n/10-2]] + words(n%10)
10 if n < 1000:
11 return [to19[n/100-1]] + ['Hundred'] + words(n%100)
12 for p, w in enumerate(('Thousand', 'Million', 'Billion'), 1):
13 if n < 1000**(p+1):
14 return words(n/1000**p) + [w] + words(n%1000**p)
15 return ' '.join(words(num)) or 'Zero'