/ src / helper_random.py
helper_random.py
 1  """Convenience functions for random operations. Not suitable for security / cryptography operations."""
 2  
 3  import random
 4  
 5  
 6  NoneType = type(None)
 7  
 8  
 9  def seed():
10      """Initialize random number generator"""
11      random.seed()
12  
13  
14  def randomshuffle(population):
15      """Method randomShuffle.
16  
17      shuffle the sequence x in place.
18      shuffles the elements in list in place,
19      so they are in a random order.
20      As Shuffle will alter data in-place,
21      so its input must be a mutable sequence.
22      In contrast, sample produces a new list
23      and its input can be much more varied
24      (tuple, string, xrange, bytearray, set, etc)
25      """
26      random.shuffle(population)
27  
28  
29  def randomsample(population, k):
30      """Method randomSample.
31  
32      return a k length list of unique elements
33      chosen from the population sequence.
34      Used for random sampling
35      without replacement, its called
36      partial shuffle.
37      """
38      return random.sample(population, k)
39  
40  
41  def randomrandrange(x, y=None):
42      """Method randomRandrange.
43  
44      return a randomly selected element from
45      range(start, stop). This is equivalent to
46      choice(range(start, stop)),
47      but doesnt actually build a range object.
48      """
49      if isinstance(y, NoneType):
50          return random.randrange(x)  # nosec
51      return random.randrange(x, y)  # nosec
52  
53  
54  def randomchoice(population):
55      """Method randomchoice.
56  
57      Return a random element from the non-empty
58      sequence seq. If seq is empty, raises
59      IndexError.
60      """
61      return random.choice(population)  # nosec