3 ms·
> Please tell me how to vectorize this Python code. Go on, I'm waiting. You can't entirely get rid of the loops, but at least the inner one can be vectorized,
by xg15 1y ago
> Please tell me how to vectorize this Python code. Go on, I'm waiting.
You can't entirely get rid of the loops, but at least the inner one can be vectorized, I think. That would reduce the "pythonic runtime" from squared to linear.
Maybe something like this?
result = np.full((limit+1,), True, dtype=bool)
result[0] = False
indices = np.arange(len(result))
for i in range(2, len(result)):
result[indices[i:] * i] = False
This is just out of my head, so may contain bugs. Also, the indices array may need to be clamped, not sure right now if numpy accepts out-of-bounds indices.