'Python random.shuffle() returning different results when function passed in
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?
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ralphmerridew |
| Solution 2 | Tim Roberts |
| Solution 3 | tdelaney |
