python - 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?
解决方案
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
推荐阅读
- c# - 有没有更有效的方法来对这些字典进行排序
- amazon-ec2 - 如何以编程方式确定给定区域的 AWS 优化 ECS 映像?
- git - Git预提交没有提交
- python - 使用 Python 进行游戏 - 添加选项“重启游戏”
- php - Array_map() 一个简单的 cURL 函数
- javascript - 比较两个数组并添加新标志
- asp.net - VB ASP.NET WebForms 应用程序突然拒绝启动
- javascript - Highcharter 链接地图和线图
- twitter-bootstrap - 在 Bootstrap 中为部分设置全宽的更简洁方法
- javascript - Why doesn't my border change to the specified color?