The problem
Full the greatestProduct
technique in order that it’ll discover the best product of 5 consecutive digits within the given string of digits.
Instance:
greatestProduct("123834539327238239583") # ought to return 3240
The enter string all the time has greater than 5 digits.
The answer in Python code
Possibility 1:
from itertools import islice
from functools import cut back
def greatest_product(n):
numbers=[int(value) for value in n]
end result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)]
return max(end result)
Possibility 2:
def greatest_product(n):
L=[]
L1=[]
for i in n:
L.append(int(i))
for i in vary(len(L)-4):
a=(L[i])*(L[i+1])*(L[i+2])*(L[i+3])*(L[i+4])
L1.append(a)
return max(L1)
Possibility 3:
from math import prod
def greatest_product(s, m=0):
for i in vary(0, len(s)-4):
m = max(m, prod(map(int,s[i:i+5])))
return m
Take a look at circumstances to validate our answer
take a look at.describe("Fundamental checks")
take a look at.assert_equals(greatest_product("123834539327238239583"), 3240)
take a look at.assert_equals(greatest_product("395831238345393272382"), 3240)
take a look at.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
take a look at.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
take a look at.assert_equals(greatest_product("02494037820244202221011110532909999"), 0)