python中用于从列表中查找数字的函数/循环

python中用于从列表中查找数字的函数/循环,python,python-3.x,Python,Python 3.x,有没有办法找到我可以从数字列表中选择的最大数字,总和不应该超过15。例:A=[2,5,3,1,10,4,5,9],B=15输出:5 到目前为止,我已经尝试过: A,B = map(int,input().split(" ")) A = list(map(int,input().split(" "))) A.sort() 对列表进行排序。循环遍历列表,求和到当前循环索引。如果结果大于15,则返回上一个索引 A= [2,5,3,1,10,4,5,9] A.sort() for i in range

有没有办法找到我可以从数字列表中选择的最大数字,总和不应该超过15。例:A=[2,5,3,1,10,4,5,9],B=15输出:5

到目前为止,我已经尝试过:

A,B = map(int,input().split(" "))
A = list(map(int,input().split(" ")))
A.sort()

对列表进行排序。循环遍历列表,求和到当前循环索引。如果结果大于15,则返回上一个索引

A= [2,5,3,1,10,4,5,9]
A.sort()
for i in range(len(A)):
    if sum(A[:i]) > 15:
        print(i-1)
        break
输出:

5

与@J.D.的答案类似。但我们可以使用变量
sum
每次添加一个元素并检查,而不是每次都计算
sum

>>> A = [2,5,3,1,10,4,5,9]
>>> A.sort()
>>> sum = 0
>>> for i in range(len(A)):
...   sum += A[i]
...   if sum > 15:
...     print(i)
...     break
... 
5

您还可以扩展@J.D.的方法并使用numpy。您可以执行数组的累积和,然后检查每个元素的和是否超过15

import numpy as np

a = np.array([2, 5, 3, 1, 10, 4, 5, 9]).sort()

cum_sum =  np.cumsum(a)<16 # returns an array of bools

print(cum_sum.sum())

你说的“最大数量”是什么意思?所有可能的组合?对列表进行排序,然后遍历列表,直到运行总数大于15。是,但数字不应超过15,输出应显示5。@chepner是正确的。将列表按升序排序,然后数一数可以累加的项目,直到超过15个,然后返回计数器。然后学习如何编码:-这比从SO复制/粘贴答案更有益。这是低效的;您不需要在每次迭代中重新汇总每个片段。@chepner-您100%正确:)它应该是
returni
5
# Precondition: a must be in monotonically increasing order
def max_numbers(a, b):
    s = 0
    for i, n in enumerate(a):
        s += n
        if s > b:
            return i

print(max_numbers(a, b))