定义获取lis中最高乘积对的函数

2024-06-09 16:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一个函数,它给出列表中最高相邻元素对的乘积。对于我的代码

gala = [1, 2, 3, 4, 5]
def adjacentElementsProduct(inputArray):
    for i in range(len(inputArray)):
        if inputArray[i] * inputArray[i+1] > inputArray[i+1] * inputArray[i+2]:
            return  inputArray[i] * inputArray[i+1] 
    elif inputArray[i+1] * inputArray[i+2] > inputArray[i] * inputArray[i+1] and inputArray[i+1] * inputArray[i+2] > inputArray[i+2] * inputArray[i+3]:
        return  inputArray[i+1] * inputArray[i+2]
    elif inputArray[i+2] * inputArray[i+3] > inputArray[i+1] * inputArray[i+2] and inputArray[i+2] * inputArray[i+3] > inputArray[i+3] * inputArray[i+4]:
         return  inputArray[i+2] * inputArray[i+3]
    else:
        return inputArray[i+3] * inputArray[i+4] 
return adjacentElementsProduct

adjacentElementsProduct(gala)

这里的输出是20(因为4x5是最高的相邻对)。此函数适用于给定的列表,即使我更改了数字及其符号的顺序。但是,如果列表的长度更改,则代码将中断。如果名单是

gala = [1, -6]

或者

gala = [2, 5, 7, -9, 10, 0, 11]

我希望函数的第一个列表的输出是-6,第二个是35。但我的函数对这样的列表是无效的。你知道吗


Tags: and函数代码in元素列表forreturn
2条回答

对@ChihebNexus方法的修改:

from operator import mul

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(map(mul, elm, elm[1:]))

更简短的版本:

def adjacentElementsProduct(elm):
   return max(map(mul, elm, elm[1:])) if len(elm) < 2 else None

还有一个:

from operator import mul
from itertools import starmap

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(starmap(mul, zip(elm, elm[1:])))

如果我正确理解了你的问题,我认为你的职能可以简化为:

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(k*v for k, v in zip(elm, elm[1:]))

所以:

>>> adjacentElementsProduct([1, 2, 3, 4, 5])
20
>>> adjacentElementsProduct([1, -6])
-6
>>> adjacentElementsProduct([2, 5, 7, -9, 10, 0, 11])
35

相关问题 更多 >