Skip to content

Commit 689e934

Browse files
Solution to Problem 17
1 parent 46b4e51 commit 689e934

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Project Euler/Problem 17/sol1.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from __future__ import print_function
2+
'''
3+
Number letter counts
4+
Problem 17
5+
6+
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.
7+
8+
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
9+
10+
11+
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen)
12+
contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
13+
'''
14+
15+
ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] #number of letters in zero, one, two, ..., nineteen (0 for zero since its never said aloud)
16+
tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] #number of letters in twenty, thirty, ..., ninety (0 for numbers less than 20 due to inconsistency in teens)
17+
18+
count = 0
19+
20+
for i in range(1, 1001):
21+
if i < 1000:
22+
if i >= 100:
23+
count += ones_counts[i/100] + 7 #add number of letters for "n hundred"
24+
25+
if i%100 is not 0:
26+
count += 3 #add number of letters for "and" if number is not multiple of 100
27+
28+
if 0 < i%100 < 20:
29+
count += ones_counts[i%100] #add number of letters for one, two, three, ..., nineteen (could be combined with below if not for inconsistency in teens)
30+
else:
31+
count += ones_counts[i%10] + tens_counts[(i%100-i%10)/10] #add number of letters for twenty, twenty one, ..., ninety nine
32+
else:
33+
count += ones_counts[i/1000] + 8
34+
35+
print(count)

0 commit comments

Comments
 (0)