From 2b9ef1451d10775c31f651f21e64bab70c9522f7 Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Fri, 19 Jan 2018 15:29:33 +0530 Subject: [PATCH] shuffle --- README.md | 28 ++++++++++++++++++++++++++++ snippets/deep_flatten.md | 1 + snippets/shuffle.md | 27 +++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 snippets/shuffle.md diff --git a/README.md b/README.md index c211d25f0..92c9ab1a9 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ def spread(arg): + ``` ```python @@ -233,6 +234,33 @@ def min_n(arr, n=1): min_n([1, 2, 3]) # [1] min_n([1, 2, 3], 2) # [1,2] ``` +### shuffle + +Randomizes the order of the values of an list, returning a new list. + +Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. + +```python + +from copy import deepcopy +from random import randint + + +def shuffle(arr): + temp_arr = deepcopy(arr) + m = len(temp_arr) + while(m): + m -= 1 + i = randint(0, m) + temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] + return temp_arr + +``` + +``` python +foo = [1,2,3] +shuffle(foo) # [2,3,1] , foo = [1,2,3] +``` ### spread Implements javascript's spread syntax as a function. Flattens the list(non-deep) and returns an list. diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index a683fd4b0..924e65a5a 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -24,6 +24,7 @@ def spread(arg): + ``` ```python diff --git a/snippets/shuffle.md b/snippets/shuffle.md new file mode 100644 index 000000000..efb12c427 --- /dev/null +++ b/snippets/shuffle.md @@ -0,0 +1,27 @@ +### shuffle + +Randomizes the order of the values of an list, returning a new list. + +Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. + +```python + +from copy import deepcopy +from random import randint + + +def shuffle(arr): + temp_arr = deepcopy(arr) + m = len(temp_arr) + while(m): + m -= 1 + i = randint(0, m) + temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] + return temp_arr + +``` + +``` python +foo = [1,2,3] +shuffle(foo) # [2,3,1] , foo = [1,2,3] +``` \ No newline at end of file