Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3
- """ One-passage list randomizer: based on a generator """
- import random as r
- class Shufflable:
- """ Shufflable objects """
- def __init__(self, lst=None):
- self.lst = lst
- self.output = list()
- self.lst_len = len(self.lst)
- self.indices_list = list(range(self.lst_len))
- def yield_unique_random(self):
- """ Return unique random numbers """
- for i in range(self.lst_len - 1, -1, -1):
- yield self.indices_list.pop(r.randint(0, i))
- def shuffle(self):
- """ Shuffle the list """
- if self.lst:
- for i in self.yield_unique_random():
- self.output.append(self.lst[i])
- self.lst = self.output
- return self.lst
- NUMBERS = Shufflable(list(range(16)))
- print(NUMBERS.shuffle())
- WORDS = Shufflable(["foo", "bar", "baz", "ham", "spam", "eggs"])
- print(WORDS.shuffle())
- # [10, 14, 3, 1, 11, 8, 0, 7, 5, 13, 4, 9, 12, 6, 15, 2]
- # ['bar', 'eggs', 'ham', 'foo', 'spam', 'baz']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement