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 :
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