ege Selcuk
ege Selcuk

Reputation: 237

Adding through an array with np.where function Numpy Python

I am trying to write a function where it adds the Sequence one at a time until the Number is reached. So since the the sum of the Sequence array is 21 and not 45 it will add the first element of the Sequence 3 to the Sequence so it becomes [3, 7, 11, 3]. Since [3, 7, 11, 3] is equal to 24 and is lower than 45 the next element in the Sequence is going to be added which is 7, the Sequence is updated to be [3, 7, 11, 3, 7] and so on until Number> np.sum([Sequence] is does not return True. The np.where function below is faulty how can I fix it?

Code:

Number = 45
Number2= 46
Sequence = np.array([3, 7, 11])
p = 0
np.where(Number> np.sum([Sequence]),np.append(Sequence,Sequence[p], p+= 1))
np.where(Number2> np.sum([Sequence]),np.append(Sequence,Sequence[p], p+= 1))

Expected Output

Number = [3,7,11,3,7,11,3]
Number2 = [3,7,11,3,7,11,3,7]

Upvotes: 0

Views: 196

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54743

I'm not convinced this can be done as a one-liner. The second and third parameters to np.where are supposed to be sequences. It's easy as a loop:

seq45 = []
for n in itertools.cycle(Sequence):
    seq45.append(n)
    if sum(seq45) >= 45: break

Upvotes: 1

Related Questions