Last active
August 22, 2018 05:41
-
-
Save krsnvijay/258782513b1bd41fdca28ca9bdecb389 to your computer and use it in GitHub Desktop.
Select a random element from a list without same selection consecutively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def random_choice(list_data): | |
'''Select a random element from a list without same selection consecutively | |
Args: | |
list_data: List of elements to select from | |
Returns: | |
Infinite generator of random selections | |
''' | |
#shallow copy | |
data = list_data[:] | |
#get a random index from the full range of list | |
rnd_idx = random.randrange(len(data)) | |
yield data[rnd_idx] | |
#swap last element with current random element | |
data[-1], data[rnd_idx] = data[rnd_idx], data[-1] | |
while(True): | |
#get a random index from the reduced range of list | |
rnd_idx = random.randrange(len(data) - 1) | |
yield data[rnd_idx] | |
#swap last element with current random element | |
data[-1], data[rnd_idx] = data[rnd_idx], data[-1] | |
if __name__ == '__main__': | |
data = [9, 1, 3, 8, 6, 4, 5, 2, 7] | |
for element in random_choice(data): | |
print(element) | |
if input('generate(y/n)') != 'y': | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A small bug is there 😄