diff options
author | William Carroll <wpcarro@gmail.com> | 2020-03-06T17·54+0000 |
---|---|---|
committer | William Carroll <wpcarro@gmail.com> | 2020-03-06T18·45+0000 |
commit | b04b1dafd2834570c53dc99eed07a309071ed40f (patch) | |
tree | 45971ed7ccc4404a0051c6d803c6b7988a622662 /scratch/deepmind/part_two/shuffle.py | |
parent | a9ac4f925b8d8c52915e5f1f4419d5570086cd8a (diff) |
Implement an in-place shuffling algorithm
I believe this may be the Fisher-Yates shuffle, but I'm not sure.
Diffstat (limited to 'scratch/deepmind/part_two/shuffle.py')
-rw-r--r-- | scratch/deepmind/part_two/shuffle.py | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/scratch/deepmind/part_two/shuffle.py b/scratch/deepmind/part_two/shuffle.py new file mode 100644 index 000000000000..fdc5a8bd80ab --- /dev/null +++ b/scratch/deepmind/part_two/shuffle.py @@ -0,0 +1,20 @@ +import random + + +def get_random(floor, ceiling): + return random.randrange(floor, ceiling + 1) + + +def shuffle(xs): + n = len(xs) + for i in range(n - 1): + j = get_random(i + 1, n - 1) + xs[i], xs[j] = xs[j], xs[i] + + +sample_list = [1, 2, 3, 4, 5] +print('Sample list:', sample_list) + +print('Shuffling sample list...') +shuffle(sample_list) +print(sample_list) |