Exercise: Shuffling
Define a function shuffle(seq) that returns a randomly shuffled version of the input sequence seq without modifying the original sequence. Use the random module.
import random
def shuffle(seq):
"""Return a randomly shuffled version of seq.
>>> shuffle([1, 2, 3])
[2, 1, 3] # example output; actual output will vary
>>> shuffle(['a', 'b', 'c', 'd'])
['c', 'a', 'd', 'b'] # example output; actual output will vary
"""
Notes and criteria
- You cannot use any built-in randomization functions that directly shuffle or sample from sequences.
- You are allowed to use the
randommodule to generate random numbers. - All auxiliary functions, e.g. for removing an element from a sequence, must be implemented by yourself.
- Solve it with
whileand withprocfrom funcutils.
Solutions
With proc:
def shuffle(seq):
"""Non-mutating shuffle of seq"""
from funcutils import proc
from random import randint
return proc(([], seq),
lambda s:s[1],
lambda s: (lambda r:
(s[0]+[s[1][r]], s[1][0:r]+s[1][r+1:]))
(randint(0, len(s[1])-1)))[0]
The above code is cryptic on purpose. If you can work out how my update function works, you are getting well adapted to functional programming. With a separate remove_at function like:
remove_at = lambda seq, index: seq[0:index] + seq[index+1:]
the update function becomes a little clearer:
lambda s: (lambda r:
(s[0]+[s[1][r]], remove_at(s[1], r)))
(randint(0, len(s[1])-1))
But still the lambda-in-lambda may be perplexing. We will deal with this kind of constructs later. You can simply use def:
def update(s):
r = randint(0, len(s[1])-1)
return (s[0]+[s[1][r]], remove_at(s[1], r))
Library
import random
items = [1, 2, 3, 4, 5]
shuffled_items = random.sample(items, len(items))
print(shuffled_items) # Output: A randomly shuffled version of items