- Place import names at top of script
I am sure you know if you copy paste your code into a console as is, it will raise NameErrors.
Put the following:
from functools import reduce from itertools import islice from math import prod At the top of script.
Your second function is actually quite effictive, but not as effictive as it can be, you made a simple mistake, max can return the maximum value of more than two numbers, its arguments can be infinitely many or an iterable.
So it should be written as this:
def greatest_product(s): return max(prod(map(int,s[i:i+5]i+4])) for i in range(len(s)-4)) Then, to generalize it, as you can see, if you need max product of 4 numbers the first number is 54, so if you need max product of 13 numbers the first number should be 1413, just pass two arguments to the function:
def greatest_product(s, n=13): return max(prod(map(int,s[i:i+n+1]i+n])) for i in range(len(s)-n)) Full code:
from math import prod def greatest_product(s, n=13): return max(prod(map(int,s[i:i+n+1]i+n])) for i in range(len(s)-n))