1

I define a tuple called states in my test environment. I then wish to step through this tuple in a random manner as I test my system:

st = time.time()
for s in sorted(states,key=lambda k: random.random()):
    my_system.set_state(s)
    test.confirm_state(s) 

Each state should only be visited once. Is this the most pythonic way of shuffling my tuple?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • 1
    You are using exactly what I advocated before. Since `random.shuffle()` would require you to create a list copy of the tuple first, I'd say your approach is fine. Closing as a dupe, as your basic question is essentially primarily opinion based. – Martijn Pieters Mar 10 '15 at 07:48

1 Answers1

4

Python comes with batteries included. Use random.shuffle on a sequence.

You must be aware that random.shuffle operates in place on a mutable sequence, which is why it does not return the list itself.

l = list(states)
random.shuffle(l) # random.shuffle is returning None
for x in l:
    # do stuff
Pierre de Buyl
  • 7,074
  • 2
  • 16
  • 22
  • Now you have 3 lines instead of 1. Why is this more pythonic than what the OP has? :-P – Martijn Pieters Mar 10 '15 at 07:50
  • You have a point, as always :) Is shortness more pythonic than using what the library provides? –  Mar 10 '15 at 07:52
  • 1
    Pythonicness is in the eye of the beholder. `sorted()` is also something the library provides, giving it `random.random()` as a key is just as pythonic, and it works just as well. – Martijn Pieters Mar 10 '15 at 07:53
  • 1
    `len(set(tuple(sorted(range(3), key=lambda x: random.randrange(2))) for i in range(10000))) == 5` but there are 6 permutations of `[0, 1, 2]`. Using `key=` can't generate all permutations with equal probability unless `` doesn't generate duplicates. In particular, the algorithm of `sorted` (timsort) is stable and thus can't generate `(2, 1, 0)` using `randrange(2)` as key (proof left for the reader). That's a strawman random-key, granted, but I hope it gets the point across: watch out for duplicate random keys! – Jonas Kölker Nov 09 '16 at 14:32