0

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]
3
  • Python evaluates function arguments first, and then passes in the results. where is a function, not an iterator. Practice with where in an interactive session before trying to do something fancy like this. Commented Mar 5, 2021 at 6:16
  • Except for functions like np.cumsum most numpy functions operate on their inputs 'in-parallel', as whole arrays.. They do not operate sequentially. Lists are better for sequential tasks like yours. Commented Mar 5, 2021 at 6:25
  • Is there anyway I could implant what I am trying to do with a pandas module or np.cumsum Commented Mar 5, 2021 at 21:51

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to use numpy functions since its more optimized but thanks anyways.
Confucious say, a working non-optimal solution is better than a non-working optimized solution.... You can of course make seq45 an np.array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.