Consecutive element maximum product in Python

PythonServer Side ProgrammingProgramming

Python has great libraries to manipulate data. We may come across a need to find the maximum product of two consecutive numbers which are part of the big string. In this article we will see the ways to achieve that.

With zip and max

We convert the string into a list. Then create pairs from the consecutive elements with help of slicing. Applying * we multiply the pair and then take the max value from the result of the multiplication from each of the pairs.

Example

 Live Demo

Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(int(a) * int(b) for a, b in zip(Astring, Astring[1:]))
# Result
print("The maximum consecutive product is : " ,res)

Output

Running the above code gives us the following result −

Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40

With map and max

We take a similar approach as above. But we use map function to keep generating the pair of consecutive integers. Then use the mul function from operator module to multiply the numbers in this pair. Finally apply the max function to get the max value of the result.

Example

from operator import mul
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(map(mul, map(int, Astring), map(int, Astring[1:])))
# Result
print("The maximum consecutive product is : " ,res)

Output

Running the above code gives us the following result −

Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40
raja
Published on 20-May-2020 13:59:53
Advertisements