MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solution

Function solution

project_euler/problem_017/sol1.py:19–59  ·  view source on GitHub ↗

Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19

(n: int = 1000)

Source from the content-addressed store, hash-verified

17
18
19def solution(n: int = 1000) -> int:
20 """Returns the number of letters used to write all numbers from 1 to n.
21 where n is lower or equals to 1000.
22 >>> solution(1000)
23 21124
24 >>> solution(5)
25 19
26 """
27 # number of letters in zero, one, two, ..., nineteen (0 for zero since it's
28 # never said aloud)
29 ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
30 # number of letters in twenty, thirty, ..., ninety (0 for numbers less than
31 # 20 due to inconsistency in teens)
32 tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]
33
34 count = 0
35
36 for i in range(1, n + 1):
37 if i < 1000:
38 if i >= 100:
39 # add number of letters for "n hundred"
40 count += ones_counts[i // 100] + 7
41
42 if i % 100 != 0:
43 # add number of letters for "and" if number is not multiple
44 # of 100
45 count += 3
46
47 if 0 < i % 100 < 20:
48 # add number of letters for one, two, three, ..., nineteen
49 # (could be combined with below if not for inconsistency in
50 # teens)
51 count += ones_counts[i % 100]
52 else:
53 # add number of letters for twenty, twenty one, ..., ninety
54 # nine
55 count += ones_counts[i % 10]
56 count += tens_counts[(i % 100 - i % 10) // 10]
57 else:
58 count += ones_counts[i // 1000] + 8
59 return count
60
61
62if __name__ == "__main__":

Callers 1

sol1.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected