Gryfit
Gryfit

Reputation: 23

How to get random index of the array without current idx?

I'm iterating over a list (numpy array with one dimension to be exact) and I need to pick an index form this list that is random and different than current iterator.

The most important thing is constant and equal probability over the range.

list = ['a','b','c','d']
for idx , e in enumerate(list):
  return random.randrange(len(list)-1) # but without possibility of geting idx

-- EDIT -- Wouldnt that work:

    x = np.array([1,2,3,4])
    for idx, e in enumerate(x):
        l = list(range(0, len(x)))
        l.pop(idx)
        res = random.choice(l)
        print(idx, res)

Upvotes: 0

Views: 282

Answers (3)

Josmy
Josmy

Reputation: 426

What if you add an if statement to check whether the random number you get is different from the iterator?

import random

list1 = ['a','b','c','d']
for idx, e in enumerate(list1):
   randnum = random.randrange(len(list1)-1)
if randnum != idx:
    return randnum

One more advice: since the list library is reserved by python. better not use it as a variable name.

Upvotes: 0

RedstonekPL
RedstonekPL

Reputation: 13

You could try using

list = ['a', 'b', 'c', 'd']
for idx, e in enumerate(list):
    temp = math.randrange(0, len(list)) # You would use -1, if it was randint()
    while temp == idx:
        temp = math.randrange(0, len(list))
    return temp

Upvotes: 0

Lydia van Dyke
Lydia van Dyke

Reputation: 2516

Depending on how large the list is, the chance of accidentally hitting idx might be small enough. So I usually do something like this:

def randrange(n, without=None):
    while True:
        s = random.randrange(n)
        if s != without:
            return s

To use it, just replace your return statement with return randrange(len(list)-1, idx)

Upvotes: 1

Related Questions