buzhidao buzhidao - 1 year ago 77
Python Question

random flip m values from an array

I have an array with length

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

there are two cases,
case is a special case. It can be discussed separately, and

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):

are tens and
are hundreds.

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.