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

Faster list manipulation

I have a large numpy array whNumPylements I individually want to multiply with other indexes and then sum up. My current code is relatively slow, does anyone have an idea how I could make it faster:

result = 0
n = 1
int_array = np.array((3,16,3,29,36))
for i in int_array:
    result += int(i) * n
    n *= 10

>Solution :

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

In every iteration 10 * prev(10 * ...), So you can use 10 ^ [0, 1, 2, ...] = [1, 10, 100, ...] with numpy.array & numpy.power. Then you need [1*int_arr[0], 10*int_arr[1], ...]. At the end, you need numpy.sum().

res = (np.power(10, np.arange(int_array.shape[0])) * int_array).sum()

print(res)

Output:

389463
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