Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Array Computations: get two values per item

I’m trying to get a list with all numbers that are in the form 6n+1 or 6n-1.
Currently I have this:

n = 100000000
l = int(n/6)
f1 = lambda x: (6*x)-1
f3 = lambda x: (6*x)+1
primeCandidate = [f(i) for i in range(1,l+1) for f in (f1,f3))]

This works nicely, and it gets me 2 values on the list per i, but I was wondering if I could do something similar with NumPy arrays

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How about this. When you divide a number by 6, the modulo has to be either 1 or 5:

arr = np.arange(2, n)
out = arr[np.isin(np.mod(arr, 6), [1,5])]

Test:

assert arr[np.isin(np.mod(arr, 6), [1,5])].tolist() == [f(i) for i in range(1,l+1) for f in (f1,f3)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading