|
4 | 4 | Note: As 1! = 1 and 2! = 2 are not sums they are not included.
|
5 | 5 | """
|
6 | 6 |
|
7 |
| - |
8 |
| -def factorial(n: int) -> int: |
9 |
| - """Return the factorial of n. |
10 |
| - >>> factorial(5) |
11 |
| - 120 |
12 |
| - >>> factorial(1) |
13 |
| - 1 |
14 |
| - >>> factorial(0) |
15 |
| - 1 |
16 |
| - >>> factorial(-1) |
17 |
| - Traceback (most recent call last): |
18 |
| - ... |
19 |
| - ValueError: n must be >= 0 |
20 |
| - >>> factorial(1.1) |
21 |
| - Traceback (most recent call last): |
22 |
| - ... |
23 |
| - ValueError: n must be exact integer |
24 |
| - """ |
25 |
| - |
26 |
| - if not n >= 0: |
27 |
| - raise ValueError("n must be >= 0") |
28 |
| - if int(n) != n: |
29 |
| - raise ValueError("n must be exact integer") |
30 |
| - if n + 1 == n: # catch a value like 1e300 |
31 |
| - raise OverflowError("n too large") |
32 |
| - result = 1 |
33 |
| - factor = 2 |
34 |
| - while factor <= n: |
35 |
| - result *= factor |
36 |
| - factor += 1 |
37 |
| - return result |
| 7 | +from math import factorial |
38 | 8 |
|
39 | 9 |
|
40 | 10 | def sum_of_digit_factorial(n: int) -> int:
|
41 |
| - """ |
| 11 | + """ |
42 | 12 | Returns the sum of the digits in n
|
43 | 13 | >>> sum_of_digit_factorial(15)
|
44 | 14 | 121
|
45 | 15 | >>> sum_of_digit_factorial(0)
|
46 | 16 | 1
|
47 | 17 | """
|
48 |
| - return sum(factorial(int(digit)) for digit in str(n)) |
| 18 | + digits = list(map(int, str(n))) |
| 19 | + summ = sum(factorial(digit) for digit in digits) |
| 20 | + return summ |
49 | 21 |
|
50 | 22 |
|
51 | 23 | def compute() -> int:
|
52 | 24 | """
|
53 |
| - Returns the sum of all numbers whose |
| 25 | + Returns the sum of all numbers whose |
54 | 26 | sum of the factorials of all digits
|
55 | 27 | add up to the number itself.
|
56 | 28 | >>> compute()
|
57 | 29 | 40730
|
58 | 30 | """
|
59 |
| - return sum( |
60 |
| - num |
61 |
| - for num in range(3, 7 * factorial(9) + 1) |
62 |
| - if sum_of_digit_factorial(num) == num |
63 |
| - ) |
| 31 | + limit = 7 * factorial(9) |
| 32 | + nums = [num for num in range(3, limit) if sum_of_digit_factorial(num) == num] |
| 33 | + return sum(nums) |
64 | 34 |
|
65 | 35 |
|
66 | 36 | if __name__ == "__main__":
|
67 |
| - print(compute()) |
| 37 | + print(f"{compute()} = ") |
0 commit comments