我需要 python 代码来获取 python 列表中的某些 k 个连续数字的总和
I need to python code to get sum of some of its k consecutive numbers in a list in python
#给定整数数组,求其中 k 个连续元素的总和。
#示例输入:
#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`
您的问题不清楚,但假设您需要一个函数来 return 列表中最高的一对数字的总和:
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
#给定整数数组,求其中 k 个连续元素的总和。
#示例输入: #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`
您的问题不清楚,但假设您需要一个函数来 return 列表中最高的一对数字的总和:
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