Adopted new convention from template

This commit is contained in:
David Doblas Jiménez 2022-09-21 20:46:34 +02:00
parent 4bbfd94c64
commit 609a2f9264

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python
""" """
Created on 28 Abr 2017 Created on 28 Abr 2017
@ -9,14 +9,29 @@ Solution for problem 8 of Project Euler
https://projecteuler.net/problem=8 https://projecteuler.net/problem=8
""" """
import collections
from itertools import islice
from utils import timeit from utils import timeit
# recipe from more-itertools
def sliding_window(iterable, n):
# sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG
it = iter(iterable)
window = collections.deque(islice(it, n), maxlen=n)
if len(window) == n:
yield tuple(window)
for x in it:
window.append(x)
yield tuple(window)
@timeit("Problem 8") @timeit("Problem 8")
def compute(): def compute():
""" """
The four adjacent digits in the 1000-digit number that have the The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832. greatest product are 9 x 9 x 8 x 9 = 5832.
731671...963450 731671...963450
@ -46,22 +61,18 @@ def compute():
05886116467109405077541002256983155200055935729725 05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450 71636269561882670428252483600823257530420752963450
""" """
num = NUM.replace('\n', '').replace(' ', '') num = NUM.replace("\n", "").replace(" ", "")
adjacent_digits = 13 adjacent_digits = 13
target = len(num) - adjacent_digits #- 1 ans = 0
ans, i = 0, 0 for nums in sliding_window(num, adjacent_digits):
while i < target: prod = 1
a, j = 1, i for num in nums:
while j < (i + adjacent_digits): prod *= int(num)
a = a * int(num[j]) if prod > ans:
j += 1 ans = prod
if a > ans:
ans = a
i += 1
return ans return ans
if __name__ == "__main__": if __name__ == "__main__":
print(f"Result for Problem 8 is {compute()}")
print(f"Result for Problem 8: {compute()}")