buzhidao - 1 year ago 87

Python Question

I have an array with length

`n`

`m`

there are two cases,

`m=1`

`m=/=1`

My attempt is:

`import numpy as np`

n = 20

m = 5

#generate an array a

a = np.random.randint(0,2,n)*2-1

#random choose `m` element and flip it.

for i in np.random.randint(0,n,m):

a[m]=-a[m]

Suppose

`m`

`n`

Answer Source

To make sure we are not flipping the same element twice or even more times, we can create unique indices in that length range with `np.random.choice`

using its optional `replace`

argument set as False. Then, simply indexing into the input array and flipping in one go should give us the desired output. Thus, we would have an implementation like so -

```
idx = np.random.choice(n,m,replace=False)
a[idx] = -a[idx]
```

**Faster version :** For a faster version of `np.random_choice`

, I would suggest reading up on `this post`

that explores using `np.argpartition`

to simulate identical behavior.