shuffle
This commit is contained in:
@ -24,6 +24,7 @@ def spread(arg):
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
27
snippets/shuffle.md
Normal file
27
snippets/shuffle.md
Normal file
@ -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]
|
||||
```
|
||||
Reference in New Issue
Block a user