Reputation: 3315
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?
Upvotes: 0
Views: 588
Reputation: 77337
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.
Upvotes: 0
Reputation: 54688
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.
Upvotes: 1
Reputation: 324
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)
Upvotes: 1