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.

3
  • What sucks in sum(Score[A[i]]) Commented Feb 3, 2016 at 14:46
  • 4
    You could try total = sum(Score[x] for x in A) sum() is a builtin function. Commented Feb 3, 2016 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. Commented Feb 3, 2016 at 14:49

2 Answers 2

2

I see those solutions :

print sum(Score[x] for x in A)
print sum(map(lambda x: Score[x], A))
Sign up to request clarification or add additional context in comments.

4 Comments

Both Score and A are lists so I don't think your code works as it's written.
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)
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?
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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.