我需要python代码来获取python列表中的一些k个连续数字的总和

问题描述

#给定整数数组,求其中 k 个连续元素的总和。

#Sample 输入: #inputArray = [2,3,5,1,6] 和 k = 2

 #Sample Output:
 #arrayMaxConsecutiveSum(inputArray,k) = 8

 #Explaination:
 #All possible sums of 2 consecutive elements are:

 #2 + 3 = 5;
 #3 + 5 = 8;
 #5 + 1 = 6;
 #1 + 6 = 7.
 #Thus,the answer is 8`

解决方法

您的问题不清楚,但假设您需要一个函数来返回列表中最高数字对的总和:

def arrayMaxConsecutiveSum(inputArray,k):
    groups = (inputArray[pos:pos + k] for pos in range(0,len(inputArray),1)) # iterate through array creating groups of k length
    highest_value = 0 # start highest value at 0
    for group in groups: # iterate through groups
        if len(group) == k and sum(group) > highest_value: # if group is 2 numbers and value is higher than previous value
            highest_value = sum(group) # make new value highest
    return highest_value

inputArray = [2,3,5,1,6]

print(arrayMaxConsecutiveSum(inputArray,2))
  #8