Advertisement
Guest User

Untitled

a guest
Nov 3rd, 2019
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. # See https://softwareengineering.stackexchange.com/questions/400487
  2. # and https://softwareengineering.stackexchange.com/a/400497/350119
  3. # for what this
  4. def gen_weighted_random_fixed_sum_bool_list(size, amount_ones, weights):
  5.     import random
  6.    
  7.     # Copy the list to prevent modification of a passed-in object
  8.     weights = list(weights)
  9.    
  10.     # List of all possible indices for random.choices to choose from
  11.     all_indices = list(range(size))
  12.    
  13.     result = [0] * size
  14.     for i in range(amount_ones):
  15.         # Choose an index to set True
  16.         index = random.choices(all_indices, weights)[0]
  17.        
  18.         result[index] = 1 # Set index True
  19.         weights[index] = 0 # Remove that index from the list
  20.    
  21.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement