-2

I have a list of numbers within a range of 1 .. n I want to 'flip' some of the numbers, but it shouldnt repeat any of the existing numbers.

I imagine it this way :

  1. pick numbers to flip
  2. flip them but check that they dont repeat

Here is step 1 :

  lst = np.array([5,9,88,55,90,43])
 In [95]: z = np.random.choice(lst, 2,replace=False)
 Out[95]: array([ 9, 43])

    ixs = np.where(lst == z)[0]
    #does not guarantee that the new numbers are not already in lst!
    lst[ixs] = np.random.choice(xrange(0,n),2,replace=False)

now how do i make sure that the new random numbers dont repeat without doing checks in a loop.

Any other numpy way ?


Flip mean change from one value to another. You can think of the list of numbers as indexes to a bitarray, where the number specifies if the bit is 1.

So flipping means for every flip of 1 => 0, flip another bit from 0 => 1

in : np.array([5,9,88,55,90,43]) out: np.array([5,9,46,55,21,43])

two number was changed

sten
  • 7,028
  • 9
  • 41
  • 63
  • 3
    Could you define what `flip` means? Print upside down? Replace with a random number? So it could be the same? Maybe you could give an example for an input and desirable output? – roadrunner66 May 04 '20 at 01:31
  • Show a sample input and output. This is not clear at all. – Mad Physicist May 05 '20 at 01:32

1 Answers1

1

You can use sets.

s = set(xrange(0, n))

lst[ixs] = np.random.choice(s.difference(lst), 2, replace=False)

It's arguable if it's much more efficient, but it is certainly cleaner.

Gianluca Micchi
  • 1,584
  • 15
  • 32