mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
so easy
This commit is contained in:
parent
d99d1d27dc
commit
1b336bf09a
2 changed files with 103 additions and 0 deletions
33
interview_cake/math/in_place_shuffle.py
Normal file
33
interview_cake/math/in_place_shuffle.py
Normal file
|
@ -0,0 +1,33 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function for doing an in-place shuffle of a list.
|
||||
|
||||
The shuffle must be "uniform," meaning each item in the original list must have the same probability of ending up in each spot in the final list.
|
||||
|
||||
Assume that you have a function get_random(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
def get_random(floor, ceiling):
|
||||
return random.randrange(floor, ceiling + 1)
|
||||
|
||||
def shuffle(the_list):
|
||||
|
||||
if len(the_list) <= 1:
|
||||
return the_list
|
||||
|
||||
last_index_in_the_list = len(the_list) - 1
|
||||
|
||||
for i in range(len(the_list) - 1):
|
||||
random_choice_index = get_random(i,
|
||||
last_index_in_the_list)
|
||||
if random_choice_index != i:
|
||||
the_list[i], the_list[random_choice_index] = \
|
||||
the_list[random_choice_index], the_list[i]
|
||||
|
||||
|
||||
seed_list = [5, 2, 6, 2, 6]
|
||||
shuffle(seed_list)
|
||||
print seed_list
|
Loading…
Add table
Add a link
Reference in a new issue