Python | Sequential element of maximum product

Python Methods and Functions

Method # 1: Using max () + zip () + comprehension list

This problem can be solved with a combination of the above three functions where the max function can be used to get the maximum value, zip, and comprehension of the list, performing the task of extending the logic to the entire list.

# Python3 demo code
# Sequential maximum product element
# using zip () + max () + comprehension list

 
# initialization string

test_string = `2312231223124565128998`

  
# print orig original string

print ( "The original string: " + str (test_string))

 
# using zip () + max () + comprehension list
# Maximum product sequential element

test_string = list (test_string)

res = max ( int (a) * int (b) for a, b in zip (test_string, test_string [ 1 :]))

 
# print result

print ( "The maximum consecutive product is: " + str (res))

Output:

 The original string: 2312231223124565128998 The maximum consecutive product is: 81 

Method # 2: Using max () + map () + operator.mul

The above problem can also be solved using another combination of functions. In this combination, map functions perform the task of extending the logic to the entire list, and the mul operator is used to perform multiplication.

# Python3 demo code
# Sequential maximum product element
# using max () + map () + operator.mul

from operator import mul

  
# initialization string

test_string = `6543452345456987653234`

 
# print original line

print ( "The original string:" + str (test_string))

 
# using max () + map () + operator.mul
# Maximum product sequential

res = max ( map (mul, map ( int , test_string), map ( int , test_string [ 1 :])))

 
# print result

print ( "The maximum consecutive product is:" + str (res))

Output:

 The original string: 6543452345456987653234 The maximum consecutive product is: 72 




Get Solution for free from DataCamp guru