📜  Python|连续元素最大乘积

📅  最后修改于: 2022-05-13 01:55:17.068000             🧑  作者: Mango

Python|连续元素最大乘积

有时,我们可能会遇到一个问题,即我们需要从列表中获取 2 个数字的最大乘积,但有一个限制是让数字连续。在竞争性编程中可能会出现此类问题。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用max() + zip() + 列表理解

这个问题可以通过以上三个函数的组合来解决,其中 max函数可以用来获取最大值, zip 和 list comprehension 完成将逻辑扩展到整个列表的任务。

# Python3 code to demonstrate
# Consecutive element maximum product
# using zip() + max() + list comprehension
  
# initializing string 
test_string = '2312231223124565128998'
  
# printing original string 
print("The original string : " + str(test_string))
  
# using zip() + max() + list comprehension
# Consecutive element maximum product
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))
输出 :
The original string : 2312231223124565128998
The maximum consecutive product is : 81

方法 #2:使用max() + map() + operator.mul

上述问题也可以使用另一种功能组合来解决。在这种组合中,map 函数执行将逻辑扩展到整个列表的任务,而 mul运算符用于执行乘法。

# Python3 code to demonstrate
# Consecutive element maximum product
# using max() + map() + operator.mul
from operator import mul
  
# initializing string 
test_string = '6543452345456987653234'
  
# printing original string 
print("The original string : " + str(test_string))
  
# using max() + map() + operator.mul
# Consecutive element maximum product
res = max(map(mul, map(int, test_string), map(int, test_string[1:])))
  
# print result
print("The maximum consecutive product is : " + str(res))
输出 :
The original string : 6543452345456987653234
The maximum consecutive product is : 72