Skip to content Skip to sidebar Skip to footer

How To Use Optional Argument Of Random.shuffle In Python

From the doc of random.shuffle(x[, random]), it says: The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the functio

Solution 1:

It means you can pass in the name of a function which does not require an argument.

def foo():
    return 0.5

is such a function.

def bar(limit):
    return limit

is not, because it requires an argument limit.

Usage example:

random.shuffle(itemlist, random=foo)

If the input itemlist was [1, 2, 3] it will now be [1, 3, 2]. I have established this experimentally, and I suppose how exactly the shuffle operation uses the output from the random function could change between Python versions.

The default if you don't specify anything is the function random().

One possible use case for this is if you want predictable output e.g. for a test case. Another is if you want nonuniform distribution - for example, a random function which prefers small values over large ones, or implements e.g. Poisson or normal distribution.


Solution 2:

A 0-argument function has an empty argument list.

def random_seed():  # Zero arguments here.
  return MY_CONFIG.predictble_random_seed  # Some imaginary config.

random.shuffle(some_list, random_seed)  # Always the same shuffling.

The point of this arrangement is to allow to control the predictability of the shuffling. You can return a really random number (from timer, /dev/urandom, etc, as random.random() does) in production, and a controlled number in a test environment:

def get_random_generator(environment):
  if environment == 'test':
    return lambda: 0.5  # A 0-argument callable returning a constant.
  else:
    return random.random  # A function returning a random number.

# ... 

# The below is predictable when testing in isolation, 
# unpredictable when running in production.
# We suppose that `environment` has values like 'test' and 'prod'.
random.shuffle(entries, get_random_generator(environment))  

Solution 3:

The random parameter is the seed. Then if you always use the same seed, it always reorder your array with the same logic. See the exemple. 5 is at index 4 and go to 0. 6 go to 4 (Old index of 5) then if we reuse the same seed, 6 go the index 0 because 6 is at index 4 like 5 at the first shuffle
Exemple:

>>> import random
>>> r = random.random()
>>> r
0.4309619702601998
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(x, lambda: r)
>>> x
[5, 1, 4, 2, 6, 3]
>>> random.shuffle(x, lambda: r)
>>> x
[6, 5, 2, 1, 3, 4]
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(x, lambda: r)
>>> x
[5, 1, 4, 2, 6, 3]

Source


Post a Comment for "How To Use Optional Argument Of Random.shuffle In Python"