How to Find the Largest Product in a Series in Python


The challenge

Complete the greatestProduct method so that it’ll find the greatest product of five consecutive digits in the given string of digits.

Example:

greatestProduct("123834539327238239583") # should return 3240

The input string always has more than five digits.

The solution in Python code

Option 1:

from itertools import islice
from functools import reduce

def greatest_product(n):
    numbers=[int(value) for value in n]
    result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)]
    return max(result) 

Option 2:

def greatest_product(n):
    L=[]
    L1=[]
    for i in n:
        L.append(int(i))
    for i in range(len(L)-4):
        a=(L[i])*(L[i+1])*(L[i+2])*(L[i+3])*(L[i+4])
        L1.append(a)
    return max(L1)

Option 3:

from math import prod

def greatest_product(s, m=0):
    for i in range(0, len(s)-4):
        m = max(m, prod(map(int,s[i:i+5])))
    return m

Test cases to validate our solution

test.describe("Basic tests")
test.assert_equals(greatest_product("123834539327238239583"), 3240)
test.assert_equals(greatest_product("395831238345393272382"), 3240)
test.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
test.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
test.assert_equals(greatest_product("02494037820244202221011110532909999"), 0)