Created
August 19, 2011 15:34
-
-
Save keyo/1157087 to your computer and use it in GitHub Desktop.
Euler Project #17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
See http://projecteuler.net/index.php?section=problems&id=17 | |
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. | |
''' | |
def num_letters(number): | |
digit_len = {1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4} | |
first_two_len = {10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 00:0} | |
letter_count = 0 | |
if(number < 10): | |
return digit_len[number] | |
first_two = int("".join(list(str(number))[-2:])) | |
if(first_two not in first_two_len): | |
letter_count += digit_len[int(list(str(number))[-1])] | |
letter_count += first_two_len[int(list(str(number))[-2]+'0')] | |
else: | |
letter_count += first_two_len[first_two] | |
hundreds = int(str(number).rjust(3,'0')[-3]) | |
if(hundreds > 0): | |
if(first_two > 0): | |
#add the and in 'hundred and' | |
letter_count += 3 | |
letter_count += digit_len[hundreds] + 7 | |
first_three = first_two = int("".join(list(str(number).rjust(3,'0'))[-3:])) | |
thousands = int(str(number).rjust(4,'0')[-4]) | |
if(thousands > 0): | |
if(first_three > 0): | |
#add the and in 'thousand and' | |
letter_count += 3 | |
letter_count += digit_len[thousands] + 8 | |
return letter_count | |
print(reduce(lambda x,y:x+y, (num_letters(x) for x in range(1,1001)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment