Faster list manipulation

Question:

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
Asked By: Phönix 64

||

Answers:

I think i have understood that you want to progressively multiply each number of the array by n, and n is going to be multiplied by 10 each loop. Is that is what you want to do, I think there is nothing much to do. The only thing is that you dont need to convert i to an int, as i is already one

Answered By: lemmgua

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
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.