0

In converting a nice simple loop to a more pythonic version, I introduced a subtle (well, fine, subtle is in the eye of the beholder) bug.

The data structure is three 1D arrays:

  • sums[10] of floats
  • indices[2] of integers in [0,10); i.e., indices into sum[]
  • how_much[2] of floats

Original code:

for i in range(2):  
    sums[indices[i]] += how_much[i]

So if sums starts all zeros, and indices=[3,4] and how_much=[.1,.2], then we will set sums[3]=.1 and sums[4]=.2.

Pythonic version:

sums[indices] += how_much

All fine -- except for the corner case when indices[0] == indices[1]. So if sums again starts all zeros, indices=[3,3] and how_much=[.1, .2]... then the first loop sets sums[3]=.3, while the Pythonic "equivalent" sets sums[3]=.2.

I've not found this case specifically addressed in the documentation, but I'll concede that numpy is operating reasonably. Unfortunately, that behavior is incorrect for my application.

Can anyone think of a nice Pythonic way to implement the loop? (Of course, in real life, the arrays are much larger, and I execute the loop many times).

7
  • 4
    As a side comment, you should probably pick a different name than sum for the array, because that is already a reserved keyword, and you are overwriting it locally Commented Jul 20, 2018 at 21:12
  • where is a reserved keyword in NumPy. Commented Jul 20, 2018 at 21:14
  • 2
    @ParagS.Chandakkar Absolutely not. Moreover, since NumPy is a Python-based library, it cannot have its own reserved words. Commented Jul 20, 2018 at 21:16
  • Ok, wrong choice of words. I meant, where is a function in NumPy. Commented Jul 20, 2018 at 21:21
  • 2
    sum is also a function, not a keyword. Commented Jul 20, 2018 at 21:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.