Skip to content

Instantly share code, notes, and snippets.

@krsnvijay
Last active August 22, 2018 05:41
Show Gist options
  • Save krsnvijay/258782513b1bd41fdca28ca9bdecb389 to your computer and use it in GitHub Desktop.
Save krsnvijay/258782513b1bd41fdca28ca9bdecb389 to your computer and use it in GitHub Desktop.
Select a random element from a list without same selection consecutively
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
@sarathsp06
Copy link

A small bug is there 😄

@krsnvijay
Copy link
Author

@sarathsp06 I've added shallow copy to the original list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment