Improve Project Euler problem 092 solution 1 (#5703)

* Fix typos

* Improve solution
This commit is contained in:
Maxim Smolskiy 2021-10-31 13:38:28 +03:00 committed by GitHub
parent 568425dfd1
commit f92eac982d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -12,11 +12,14 @@ How many starting numbers below ten million will arrive at 89?
""" """
DIGITS_SQUARED = [digit ** 2 for digit in range(10)]
def next_number(number: int) -> int: def next_number(number: int) -> int:
""" """
Returns the next number of the chain by adding the square of each digit Returns the next number of the chain by adding the square of each digit
to form a neww number. to form a new number.
For example if number = 12, next_number() will return 1^2 + 2^2 = 5. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5.
Therefore, 5 is the next number of the chain. Therefore, 5 is the next number of the chain.
>>> next_number(44) >>> next_number(44)
32 32
@ -27,12 +30,15 @@ def next_number(number: int) -> int:
""" """
sum_of_digits_squared = 0 sum_of_digits_squared = 0
while number: while number:
sum_of_digits_squared += (number % 10) ** 2 sum_of_digits_squared += DIGITS_SQUARED[number % 10]
number //= 10 number //= 10
return sum_of_digits_squared return sum_of_digits_squared
CHAINS = {1: True, 58: False}
def chain(number: int) -> bool: def chain(number: int) -> bool:
""" """
The function generates the chain of numbers until the next number is 1 or 89. The function generates the chain of numbers until the next number is 1 or 89.
@ -40,7 +46,7 @@ def chain(number: int) -> bool:
following chain of numbers: following chain of numbers:
44 32 13 10 1 1. 44 32 13 10 1 1.
Once the next number generated is 1 or 89, the function returns whether Once the next number generated is 1 or 89, the function returns whether
or not the the next number generated by next_number() is 1. or not the next number generated by next_number() is 1.
>>> chain(10) >>> chain(10)
True True
>>> chain(58) >>> chain(58)
@ -48,10 +54,13 @@ def chain(number: int) -> bool:
>>> chain(1) >>> chain(1)
True True
""" """
while number != 1 and number != 89: if number in CHAINS:
number = next_number(number) return CHAINS[number]
return number == 1 number_chain = chain(next_number(number))
CHAINS[number] = number_chain
return number_chain
def solution(number: int = 10000000) -> int: def solution(number: int = 10000000) -> int: