My solutions to the problems found at Project Euler.

Jump to: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 20 | 21 | 22 | 25 | 3-2 |

Problem 17


#! /usr/bin/python
# Problem: How many letters would be required to spell out all numbers
#          in written form from 1 (one) to 1000 (one thousand).
# Solution: Implement a simple number->word converter.
#
# Notes: I took the cheap way out. I wrote a very specialized
#        number->word to make my life easier. I guess I was more
#        focused on getting the right answer than I was writing a
#        full library, which imo, is fine here.

import collections

def number_to_word(n):
  small = {0:'', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six',
           7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 
           12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen',
           16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
           20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty',
           70:'seventy', 80:'eighty', 90:'ninety'}
  if n in small:
    return small[n]

  digits = [int(s) for s in str(n)]

  if len(digits) == 2:
    return small[digits[0]*10]+small[digits[1]]
  elif len(digits) == 3:
    if n % 100 == 0:
      return small[digits[0]]+'hundred'

    if digits[1]*10+digits[2] in small:
      return small[digits[0]]+'hundred'+'and'+small[digits[1]*10+digits[2]]
    else:
      return small[digits[0]]+'hundred'+'and'+small[digits[1]*10]+small[digits[2]]
  else:
    return 'onethousand'

  print digits 

if __name__ == "__main__":
  total = 0
  for n in range(1,1001):
    print n, number_to_word(n)
    total += len(number_to_word(n))
  print total
  

jb