project euler problem 17 python

Solutions on MaxInterview for project euler problem 17 python by the best coders in the world

showing results for - "project euler problem 17 python"
Juana
11 Aug 2018
1# the final list that holds the string lengths
2addList = [] 
3
4# dictionary holding integer:corresponding word pairs
5numbersDict = { 
60:"zero",
71:"one",
82:"two",
93:"three",
104:"four",
115:"five",
126:"six",
137:"seven",
148:"eight",
159:"nine",
1610:"ten",
1711:"eleven",
1812:"twelve",
1913:"thirteen",
2014:"fourteen",
2115:"fifteen",
2216:"sixteen",
2317:"seventeen",
2418:"eighteen",
2519:"nineteen",
2620:"twenty",
2730:"thirty",
2840:"forty",
2950:"fifty",
3060:"sixty",
3170:"seventy",
3280:"eighty",
3390:"ninety"
34}
35
36### There has to be an easier way to do all this below ###
37
38def numberLetters(num):
39
40    letters = ""
41
42    if 0 < num <= 20:
43        letters += numbersDict[num]
44
45    if 21 <= num <= 99:
46        a,b = divmod(num, 10)
47        if b == 0:
48            letters += numbersDict[a*10]
49        else:
50            letters += numbersDict[a*10] + numbersDict[b]
51
52    if 100 <= num <= 999:
53        if num % 100 == 0:
54            letters += numbersDict[int(num / 100)] + "hundred"
55        else:
56            digit = int(num / 100)
57            num = num - digit * 100
58            if 0 < num <= 20:
59                letters += numbersDict[digit] + "hundredand" + numbersDict[num]
60            if 21 <= num <= 99:
61                a,b = divmod(num, 10)
62                if b == 0:
63                    letters += numbersDict[digit] + "hundredand" + numbersDict[a*10]
64                else:
65                    letters += numbersDict[digit] + "hundredand" + numbersDict[a*10] + numbersDict[b]
66    if num == 1000:
67        letters += "onethousand"
68
69    return letters
70
71for i in range(1,1001):
72    addList.append(len(numberLetters(i)))
73print(sum(addList))
74