This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Chris MacLeod

By: a guest on Dec 17th, 2008  |  syntax: Python  |  size: 0.70 KB  |  views: 435  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import random
  2.  
  3.  
  4.  
  5. def ShuffleBag(items, seed=None):
  6.     """Create a new shuffled bag using the elements in items.
  7.  
  8.    Items can be a dict of (item : frequency) pairs, or an iterable.
  9.    """
  10.     try:
  11.         items = sum(([item] * freq for (item, freq) in items.items()), [])
  12.     except AttributeError:
  13.         items = list(items)
  14.     random.seed(seed)
  15.     while True:
  16.         n = len(items)
  17.         for i in range(n):
  18.             grab = random.randint(i, n-1)
  19.             items[i], items[grab] = items[grab], items[i]
  20.             yield items[i]
  21.        
  22.  
  23.  
  24. sb = ShuffleBag([1, 2, 2, 2])
  25. print sb.next() # 1 - 25%, 2 - 75%
  26.  
  27. sb = ShuffleBag({1:1, 2:3})
  28. print sb.next() #1 - 25%, 2 - 75%
clone this paste RAW Paste Data