17.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Dictionaries that map from number to number of letters
  2. ones = {
  3. 0: 0, # 'one'
  4. 1: 3, # 'two'
  5. 2: 3,
  6. 3: 5,
  7. 4: 4,
  8. 5: 4,
  9. 6: 3,
  10. 7: 5,
  11. 8: 5,
  12. 9: 4,
  13. }
  14. teens = {
  15. 10: 3, # 'ten'
  16. 11: 6, # 'eleven'
  17. 12: 6,
  18. 13: 8,
  19. 14: 8,
  20. 15: 7,
  21. 16: 7,
  22. 17: 9,
  23. 18: 8,
  24. 19: 8,
  25. }
  26. tens = {
  27. 2: 6, # 'twenty'
  28. 3: 6, # 'thirty'
  29. 4: 5,
  30. 5: 5,
  31. 6: 5,
  32. 7: 7,
  33. 8: 6,
  34. 9: 6,
  35. }
  36. hundred = {
  37. 0: 10,
  38. 1: 13, # 'one hundred and '
  39. 2: 13, # 'two hundred and '
  40. 3: 15,
  41. 4: 14,
  42. 5: 14,
  43. 6: 13,
  44. 7: 15,
  45. 8: 15,
  46. 9: 14,
  47. }
  48. def number_length(n):
  49. if n < 10:
  50. return ones[n]
  51. elif n < 100:
  52. if n < 20:
  53. return teens[n]
  54. else:
  55. return tens[n/10] + ones[n % 10]
  56. elif n < 1000:
  57. if n % 100 == 0:
  58. return ones[n/100] + 7 # Add 7 for length of 'hundred'
  59. else:
  60. return hundred[n/100] + number_length(n % 100)
  61. def main(n):
  62. total = 0
  63. for i in xrange(1, n):
  64. total += number_length(i)
  65. return total + 11 # Add 11 for length of 'one thousand'
  66. if __name__ == "__main__":
  67. print main(1000)