From 078b2e9b2a15ec7c69c7a597a6e885651f99ea12 Mon Sep 17 00:00:00 2001 From: Bjiornulf Date: Thu, 31 Aug 2023 18:09:32 +0200 Subject: [PATCH] (#8594) Optimization : avoid `str` Dividing number number and using remainder is about 25% faster. --- project_euler/problem_034/sol1.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/project_euler/problem_034/sol1.py b/project_euler/problem_034/sol1.py index 8d8432dbbb7a..50453387429c 100644 --- a/project_euler/problem_034/sol1.py +++ b/project_euler/problem_034/sol1.py @@ -8,7 +8,7 @@ from math import factorial -DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)} +DIGIT_FACTORIAL = [factorial(d) for d in range(10)] def sum_of_digit_factorial(n: int) -> int: @@ -19,7 +19,11 @@ def sum_of_digit_factorial(n: int) -> int: >>> sum_of_digit_factorial(0) 1 """ - return sum(DIGIT_FACTORIAL[d] for d in str(n)) + s = 0 + while n != 0: + s += DIGIT_FACTORIAL[n % 10] + n //= 10 + return s def solution() -> int: