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

我正在尝试编写一个函数,该函数给出列表中最高一对相邻元素的乘积。对于我的代码,


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(因为 4 x 5 是最高的相邻对)。即使我更改了数字的顺序及其符号,此函数也适用于给定的列表。但是,如果列表的长度发生更改,则代码会中断。如果列表是


gala = [1, -6]

要么


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

我希望函数第一个列表的输出为 -6,第二个为 35。但我的函数在此类列表中会中断。


皈依舞
浏览 152回答 2
2回答

一只萌萌小番薯

如果我没有正确理解您的问题,我认为您的功能可以简化为:def adjacentElementsProduct(elm):&nbsp; &nbsp;if len(elm) < 2:&nbsp; &nbsp; &nbsp; &nbsp;return None&nbsp; &nbsp;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

缥缈止盈

方法的修改:from operator import muldef adjacentElementsProduct(elm):&nbsp; &nbsp;if len(elm) < 2:&nbsp; &nbsp; &nbsp; &nbsp;return None&nbsp; &nbsp;return max(map(mul, elm, elm[1:]))一个更短的版本:def adjacentElementsProduct(elm):&nbsp; &nbsp;return max(map(mul, elm, elm[1:])) if len(elm) < 2 else None还有一个:from operator import mulfrom itertools import starmapdef adjacentElementsProduct(elm):&nbsp; &nbsp;if len(elm) < 2:&nbsp; &nbsp; &nbsp; &nbsp;return None&nbsp; &nbsp;return max(starmap(mul, zip(elm, elm[1:])))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python