Skip to content

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
Code language: Python (python)

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)
Code language: Python (python)

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)
Code language: Python (python)

Option 3:

from math import prod def greatest_product(s, m=): for i in range(, len(s)-4): m = max(m, prod(map(int,s[i:i+5]))) return m
Code language: Python (python)

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"), )
Code language: Python (python)

See also  How to Calculate Powers of 2 in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x