1

Let's say I have a list "A" of length about 40, consisting of integers from 0 to 5, and a list "Score". I want to calculate the sum of Score[A[i]].

Of course, I can do:

sum = 0 
for x in A do:
    sum += Score[x]

But is there a faster way? I know that numpy can do multiplication of lists, but this requires some sort of indexing.

CaptainCodeman
  • 1,951
  • 2
  • 20
  • 33
  • What sucks in `sum(Score[A[i]])` – Learner Feb 03 '16 at 14:46
  • 4
    You could try `total = sum(Score[x] for x in A)` `sum()` is a builtin function. – zondo Feb 03 '16 at 14:46
  • 3
    (Because you tagged this [numpy]) If `Score` is a NumPy array you'd use `Score[A].sum()`. No particular reason to use this over native Python methods if you don't need other NumPy functions though. – Alex Riley Feb 03 '16 at 14:49

2 Answers2

2

I see those solutions :

print sum(Score[x] for x in A)
print sum(map(lambda x: Score[x], A))
cromod
  • 1,721
  • 13
  • 26
  • Both `Score` and `A` are lists so I don't think your code works as it's written. – Alex Riley Feb 03 '16 at 15:11
  • 2
    No worries - that works now, although it's probably faster to use just a generator expression in `sum`, i.e. `sum(Score[x] for x in A)` – Alex Riley Feb 03 '16 at 15:15
  • Thanks for this. But what if Score is different for each element, in other words, it's the sum of Score[i][A[i]]. Would I write sum(Score[i][A[i]]), or is there a faster way? – CaptainCodeman Feb 03 '16 at 15:34
  • Except numpy, I don't see any faster way than sum and a generator expression. I read numpy is faster but you must define your array with numpy. [See DrV's answer here](http://stackoverflow.com/questions/24578896/python-built-in-sum-function-vs-for-loop-performance). – cromod Feb 03 '16 at 15:57
1

The Python function "sum" is pretty efficient. It avoids memory overhead (I believe it is written in C) and should be a bit faster.

It would look like this

intSum = sum(array)