### Fisher-Yates shuffle in python

For a pet project I needed a array randomizer. I thought up an algorithm that I thought should work. It did, but funnily enough; I ended up re-discovering the Fisher-Yates shuffle. Here’s an implementation in Python.

import random import math def array_randomizer(arr): random.seed() index = len(arr) - 1 # print "index is ", index while index > 0: rand = math.floor(random.random() * (index + 1)) picked_element = int(rand) arr[index], arr[picked_element] = arr[picked_element], arr[index] index -= 1 return arr def analyze_array(template_arr, arr): ret = [] for element in template_arr: v = arr.index(element) ret.append(v) return ret def summarize(sum_array, val_array): for index in range(len(val_array)): sum_array[index] = val_array[index] + sum_array[index] if __name__ == '__main__': a = ['a', 'b', 'c', 'd', 'e', 'f' ] sum_array = [0.0] * 6 # initialize array with zeros runs = 100000 for i in range(0,runs): res_array = array_randomizer(a[:]) # copy array # print "random: ", res_array val_array = analyze_array(a, res_array) summarize(sum_array, val_array) print map( lambda x: x / runs, sum_array)

## Leave a Reply