Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- '''
- Let n be the number you want values to add up to.
- Generate a random sample of random size (less than n), consisting of
- values in the range 1 to n exclusive of n. Now add the endpoints 0 and n,
- and sort. Successive differences of the sorted values will sum to n.
- If you'd like to be able to specify the number of terms in the sum explicitly,
- or have it be random if unspecified, add an optional argument:
- '''
- def random_sum_to(n, num_terms = None):
- num_terms = (num_terms or random.randint(2, n)) - 1
- a = random.sample(range(1, n), num_terms) + [0, n]
- list.sort(a)
- return [a[i+1] - a[i] for i in range(len(a) - 1)]
- total = 1000
- n_terms = 20
- my_list = random_sum_to(total, n_terms)
- print(my_list)
- print(sum(my_list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement