Tuesday, April 23, 2024
HomeSoftware EngineeringMethods to Discover the Largest product in a Collection in Python

Methods to Discover the Largest product in a Collection in Python


The problem

Full the greatestProduct methodology 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 scale 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

Check instances to validate our answer

check.describe("Fundamental assessments")
check.assert_equals(greatest_product("123834539327238239583"), 3240)
check.assert_equals(greatest_product("395831238345393272382"), 3240)
check.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
check.assert_equals(greatest_product("92494737828244222221111111532909999"), 5292)
check.assert_equals(greatest_product("02494037820244202221011110532909999"), 0)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments