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

2024-09-28 17:05:10 发布

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

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

#样本输入: #输入阵列=[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`

Tags: ofsample元素output整数数组elementsall
1条回答
网友
1楼 · 发布于 2024-09-28 17:05:10

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

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

相关问题 更多 >