Advertisement
banovski

One-passage list shuffler

Sep 27th, 2024 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | Software | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. """One-passage list shuffler"""
  4.  
  5. import random as r
  6.  
  7. class Shufflable:
  8.     """Shufflable lists"""
  9.     def __init__(self, lst=None):
  10.         self.lst = lst
  11.  
  12.     def swap(self, from_index, to_index):
  13.         """Swapping values"""
  14.         temp = self.lst[from_index]
  15.         self.lst[from_index] = self.lst[to_index]
  16.         self.lst[to_index] = temp
  17.  
  18.     def shuffle(self):
  19.         """Shuffling items"""
  20.         if self.lst:
  21.             for i in range(len(self.lst)):
  22.                 target_index = r.randint(0, i)
  23.                 self.swap(i, target_index)
  24.         return self.lst
  25.  
  26. NUMBERS = Shufflable(list(range(16)))
  27. NUMBERS.shuffle()
  28.  
  29. WORDS = Shufflable(["foo", "bar", "baz", "ham", "spam", "eggs"])
  30. WORDS.shuffle()
  31.  
  32. print(NUMBERS.lst, '\n', WORDS.lst, sep='')
  33.  
  34. # [9, 0, 4, 15, 6, 13, 1, 12, 8, 14, 5, 10, 2, 11, 7, 3]
  35. # ['bar', 'ham', 'baz', 'foo', 'eggs', 'spam']
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement