Skip to content

Commit 2b6c4ff

Browse files
committed
Update sol1.py
1 parent 4bb67a0 commit 2b6c4ff

File tree

1 file changed

+10
-40
lines changed

1 file changed

+10
-40
lines changed

project_euler/problem_34/sol1.py

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,64 +4,34 @@
44
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
55
"""
66

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
388

399

4010
def sum_of_digit_factorial(n: int) -> int:
41-
"""
11+
"""
4212
Returns the sum of the digits in n
4313
>>> sum_of_digit_factorial(15)
4414
121
4515
>>> sum_of_digit_factorial(0)
4616
1
4717
"""
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
4921

5022

5123
def compute() -> int:
5224
"""
53-
Returns the sum of all numbers whose
25+
Returns the sum of all numbers whose
5426
sum of the factorials of all digits
5527
add up to the number itself.
5628
>>> compute()
5729
40730
5830
"""
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)
6434

6535

6636
if __name__ == "__main__":
67-
print(compute())
37+
print(f"{compute()} = ")

0 commit comments

Comments
 (0)