buzhidao buzhidao - 4 months ago 35
Python Question

random flip m values from an array

I have an array with length

n
, I want to randomly choose
m
elements from it and flip their value. What is the most efficient way?

there are two cases,
m=1
case is a special case. It can be discussed separately, and
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
are tens and
n
are hundreds.

Answer

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.