Search code examples
pythonsumnumbersaddition

I need to python code to get sum of some of its k consecutive numbers in a list in python


#Given array of integers, find the sum of some of its k consecutive elements.

#Sample Input: #inputArray = [2, 3, 5, 1, 6] and 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`

Solution

  • Your question is not clear but assuming you need a function to return the sum of the highest pair of numbers in your list:

    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