Advertisement
banovski

One-passage list shuffler (generator)

Sep 27th, 2024 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. """ One-passage list randomizer: based on a generator """
  4.  
  5. import random as r
  6.  
  7. class Shufflable:
  8.     """ Shufflable objects """
  9.     def __init__(self, lst=None):
  10.         self.lst = lst
  11.         self.output = list()
  12.         self.lst_len = len(self.lst)
  13.         self.indices_list = list(range(self.lst_len))
  14.  
  15.     def yield_unique_random(self):
  16.         """ Return unique random numbers """
  17.         for i in range(self.lst_len - 1, -1, -1):
  18.             yield self.indices_list.pop(r.randint(0, i))
  19.  
  20.     def shuffle(self):
  21.         """ Shuffle the list """
  22.         if self.lst:
  23.             for i in self.yield_unique_random():
  24.                 self.output.append(self.lst[i])
  25.         self.lst = self.output
  26.         return self.lst
  27.  
  28. NUMBERS = Shufflable(list(range(16)))
  29. print(NUMBERS.shuffle())
  30.  
  31. WORDS = Shufflable(["foo", "bar", "baz", "ham", "spam", "eggs"])
  32. print(WORDS.shuffle())
  33.  
  34. # [10, 14, 3, 1, 11, 8, 0, 7, 5, 13, 4, 9, 12, 6, 15, 2]
  35. # ['bar', 'eggs', 'ham', 'foo', 'spam', 'baz']
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement