ege Selcuk
ege Selcuk

Reputation: 237

Optimizing Vanilla Python with Pandas and Numpy

Is there anyway that I could make the function below faster and more optimized with pandas or numpy, the function below adds the sum of seq45 until the elements of it is equivalent or over 10000.The elements that is being added up to seq45 are 3,7,11 in order. The reason why i want to increase the speed is to have have to possibly test 10000 with larger number values like 1000000 and to be processed faster. The answer to this code was gotten from this issue: issue

Code:

Sequence = np.array([3, 7, 11])
seq45= []
for n in itertools.cycle(Sequence):
    seq.append(n)
    if sum(seq45) >= 10000: break
        
print(seq45)

Current Perfromance/ Processing time: 71.9ms

enter image description here

Upvotes: 0

Views: 334

Answers (2)

9769953
9769953

Reputation: 12201

import numpy as np

tot = 10_000
sequence = np.array([3, 7, 11])
n = tot // sequence.sum() + 1
seq45 = np.tile(sequence, n)

Note that this is not exactly equivalent, since it repeats the full sequence, not individual elements, and seq45 may thus be slightly larger.

Upvotes: 1

bb1
bb1

Reputation: 7863

You can try:

Sequence = np.array([3, 7, 11])
s = Sequence.sum()
tot = 10000

seq = list(Sequence)*(tot//s)
mod = tot%s
for n in seq:
    if mod > 0:
        seq.append(n)
        mod -= n
    else:
        break

Wall time: 57 µs

Upvotes: 1

Related Questions