Home > other >  Python random.shuffle() returning different results when function passed in
Python random.shuffle() returning different results when function passed in

Time:04-20

I'm trying to unit test some code that makes use of random.shuffle(a, func). In order to keep the ordering deterministic, I pass in a func defined as:

def func():
  return 0.1

what's strange is that the list seems to still get shuffled.

import random

def func():
  return 0.1

a = ['c', 'good', 'b', 'hello', 'a']
random.shuffle(a, func)
print(a)

random.shuffle(a, func)
print(a)

random.shuffle(a, func)
print(a)

output:

['good', 'b', 'hello', 'a', 'c']
['b', 'hello', 'a', 'c', 'good']
['hello', 'a', 'c', 'good', 'b']

What's going on here?

CodePudding user response:

Try resetting the array after each shuffle:

import random

def func():
  return 0.1

a = ['c', 'good', 'b', 'hello', 'a']
random.shuffle(a, func)
print(a)

a = ['c', 'good', 'b', 'hello', 'a']
random.shuffle(a, func)
print(a)

a = ['c', 'good', 'b', 'hello', 'a']
random.shuffle(a, func)
print(a)

CodePudding user response:

You are feeding the shuffled list to be shuffled AGAIN, so the initial conditions aren't the same. If you run the app again, you will see the same results. Notice that 'good' (the second element) ends up first. In the second one, 'b' (the second element) ends up first.

CodePudding user response:

shuffle still goes through the list, choosing items to swap, its just that its not random any more. You could do

def func():
    return .99999

to get no shuffle. This is only because of an accident of implementation. No guarantee that it will always behave that way.

  • Related