Python 通过一次添加一个数组元素来检查Numpy数组的商
我有一个np数组。我希望用户给程序一个数字,它将返回数组中的哪些数字除以数组的和大于或等于用户给出的数字。只是从左到右,不是所有可能的情况 例如:Python 通过一次添加一个数组元素来检查Numpy数组的商,python,arrays,numpy,Python,Arrays,Numpy,我有一个np数组。我希望用户给程序一个数字,它将返回数组中的哪些数字除以数组的和大于或等于用户给出的数字。只是从左到右,不是所有可能的情况 例如: x= np.array [1,2,3,4,5] userNum = input (“Enter a number: ”) #code. Say the user inputs 5. The sum of array = 15. Start at 1/15. Go until #Quotient is >= userNum. In this c
x= np.array [1,2,3,4,5]
userNum = input (“Enter a number: ”)
#code. Say the user inputs 5. The sum of array = 15. Start at 1/15. Go until
#Quotient is >= userNum. In this case, it would have to go through 3 times
#(1+2+3 = 6). Then, output the numbers it had to calculate. (output: [1 2 3]
一段时间?有没有办法使用np.cumsum?我想到了像这样运行的while循环:
Denom = (x[1]/sum(x))
#Start with dividing the first number
while Denom <= userNum
#psuedocode:
#(x[1]/sum(x)) doesn't work
#Add the next element of the array to the one(s) already added
#Denom is updated to (x[1]+x[2])/sum(x). This will continue to
#(x1[1]+x[2]+...x[n]>=userNum
#Store the numbers used in a seperate array
print 'Here are the numbers used: ' #Numbers used from array to be larger than userNum
#ex: [1 2 3]
不知道如何实现它。帮助?试试这个:
print(x[0:np.flatnonzero(x.cumsum()>userNum)[0]+1])
这应该给你使用的数字
输入:
x = np.array([3,1,2,4,5])
userNum = 7
print(x[0:np.flatnonzero(x.cumsum()>userNum)[0]+1])
输出:
[3 1 2 4]
一点解释:x.cumsum返回累积和,x.cumsum>userNum返回一个numpy数组,指示数组的每个索引的条件是否为true。在我上面发布的示例中,它x.cumsum返回[3,4,6,10,15],x.cumsum>userNum返回[False,False,False,True,True]。np.flatnonzero返回数组中非零元素的索引。在本例中,它返回数组中的True索引。您需要找到数组中第一个True的索引,因为这是最后使用的数字的索引。最后打印出从0到np.flatnonzerox.cumsum>userNum[0]使用的数字 简单地说:
x[x.cumsum()<=5]
我不明白求和的目的。你为什么要在其中包含商?工作起来很有魅力!非常感谢。