首页 > 解决方案 > How do you count the sum of all values in an array up until a point?

问题描述

Okay, so I was doing some practice problems for USACO and noticed that for one of the problems, you needed to add all values of an array up to a certain value. For an example, say that a = [0, 5, 7, 3, 9]. You need to find the value of all the sum of the numbers up to a certain value, but you don't know what the value is( Like the value could be a[2], a[3], a[4] or anything) Also, the array is different every time. How would you find the sum of all values up to a certain place in the array?

标签: pythonarrayssum

解决方案


you can find the index of the value and the sum the sublist up untill it :

arr = [0, 5, 7, 3, 9]

up_to = 3
sum(arr[:arr.index(up_to)])
>>>12

if you want to include the value:

sum(arr[:arr.index(up_to) + 1])
>>>15

推荐阅读