Search code examples
pythonsumrangeindices

How to sum up elements in list in a moving range


I'm trying to sum up elements from list in a moving range. For instance, when the user input a customized range 'n', list[0] to list[n] will be added up and stored in a new list, followed by list[1] to list[n+1] until the end. Finally the maximum number in the new list will print out. However, in my code, it seems that the elements are continuously summing up. Thanks a lot for your help.

The list is:

[5.8, 1.2, 5.8, 1.0, 6.9, 0.8, 6.0, 18.4, 18.6, 1.0, 0.8, 6.4, 12.2, 18.2, 1.4, 6.8, 41.8, 3.6, 5.2, 5.2, 4.6, 8.6, 16.6, 13.2, 9.6, 41.6, 37.2, 110.0, 30.0, 34.8, 24.6, 7.0, 13.4, 0.5, 37.0, 18.8, 20.4, 0.6, 6.4, 2.4, 1.0, 7.6, 6.6, 4.4, 2.4, 0.6, 3.2, 21.2, 28.2, 3.2, 2.4, 14.4, 0.6, 1.6, 4.4, 0.8, 0.6, 1.6, 1.0, 27.0, 52.6, 10.2, 1.0, 4.2]

My code:

days = int(input('Enter customized range: '))
n = np.arange(days) 
total = 0
count = 1
max_total = []



while (count + len(n) - 2) <= (len(rain_b) - 1):

    for i in range(count+len(n)-4, count+len(n)-2):
        total += rain_c[i]
    #print(rain_b[count+number-1])
    #total = sum([(rain_c(count+number-4)) : (count+number-2)])
        max_total.append(total)
    count += 1
    print(max_total)

Solution

  • Try this (lst being your list and n being your range):

    print(max(sum(lst[i:i+n+1]) for i in range(len(lst)-n)))
    

    So for example:

    >>> lst = [5.8, 1.2, 5.8, 1.0, 6.9, 0.8, 6.0, 18.4]
    >>> n = 5
    >>> print([sum(lst[i:i+n+1]) for i in range(len(lst)-n)])
    [21.5, 21.7, 38.9]
    >>> print(max(sum(lst[i:i+n+1]) for i in range(len(lst)-n)))
    38.9