Advertisement
jack06215

[tools] Random integer vector sum up to N

Sep 26th, 2020
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. import random
  2.  
  3. '''
  4. Let n be the number you want values to add up to.
  5. Generate a random sample of random size (less than n), consisting of
  6. values in the range 1 to n exclusive of n. Now add the endpoints 0 and n,
  7. and sort. Successive differences of the sorted values will sum to n.
  8.  
  9. If you'd like to be able to specify the number of terms in the sum explicitly,
  10. or have it be random if unspecified, add an optional argument:
  11. '''
  12.  
  13. def random_sum_to(n, num_terms = None):
  14.     num_terms = (num_terms or random.randint(2, n)) - 1
  15.     a = random.sample(range(1, n), num_terms) + [0, n]
  16.     list.sort(a)
  17.     return [a[i+1] - a[i] for i in range(len(a) - 1)]
  18.  
  19. total = 1000
  20. n_terms = 20
  21. my_list = random_sum_to(total, n_terms)
  22. print(my_list)
  23. print(sum(my_list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement