Please let me know how to bug fix this code . I tried and correct a lot of things , but I am 10 extra to the solution !
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
My solution
sd={0:0,1: 3, 2: 3, 3: 5, 4: 4, 5: 4, 6: 3, 7: 5, 8: 5, 9: 4} dd1={10:3,11:6,12:6,13:8,14:8,15:7,16:7,17:9,18:9,19:8} dd2={2:6,3:6,4:5,5:5,6:5,7:7,8:6,9:6} td= {0: 10, 1: 13, 2: 13, 3: 15, 4: 14, 5: 14, 6: 13, 7: 15, 8: 15, 9: 14} cd={0:0,1: 3, 2: 3, 3: 5, 4: 4, 5: 4, 6: 3, 7: 5, 8: 5, 9: 4,10:3,11:6,12:6,13:8,14:8,15:7,16:7,17:9,18:9,19:8} def cw(n) : if n/10 == 0 : # If the number is less than 10 execute this section return sd[n%10] elif n/100 == 0 : # If the number is less than 100 execute this section if n<20 : return(dd1[n]) # Directly map to dd1 else : return(dd2[n/10]+sd[n%10]) # If the number is > 20 do a construction elif n/1000==0 : if n%100==0: return sd[n/100] + 7 # If the number is multiples of 100 give assuming single digit and 7 for hundred elif n%100 < 20 : return td[n/100] + cd[n%100] # If 3 digit numbers not more than *20 , then direct mapping else : return td[n/100] + dd2[(n%100)/10] + sd[n%10] count = 0 for i in range(1,1000) : count = count + cw(i) print count + 11
I am getting 21134 and the answer is… (SPOILER: please hover over next line to view)
21124
VERY ANNOYING !
Advertisement
Answer
The word “eighteen” only has eight letters, not nine. Since it appears ten times in the range 1-1000, that would explain the discrepancy.
By the way, if you’re checking if n is less than 10, why not simply use n<10
instead of n/10 == 0
?