How to generate a list of random numbers so their sum would be equal to a randomly chosen number

前端 未结 3 716
面向向阳花
面向向阳花 2021-01-16 09:53

I want to generate a list of random distribution of numbers so their sum would be equal to a randomly chosen number. For example, if randomly chosen number is 5, the distrib

3条回答
  •  自闭症患者
    2021-01-16 10:21

    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.

    import random as r
    
    def random_sum_to(n):
        a = r.sample(range(1, n), r.randint(1, n-1)) + [0, n]
        list.sort(a)
        return [a[i+1] - a[i] for i in range(len(a) - 1)]
    
    print(random_sum_to(20))  # yields, e.g., [4, 1, 1, 2, 4, 2, 2, 4]
    

    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:

    import random as r
    
    def random_sum_to(n, num_terms = None):
        num_terms = (num_terms or r.randint(2, n)) - 1
        a = r.sample(range(1, n), num_terms) + [0, n]
        list.sort(a)
        return [a[i+1] - a[i] for i in range(len(a) - 1)]
    
    print(random_sum_to(20, 3))   # [9, 7, 4] for example
    print(random_sum_to(5))       # [1, 1, 2, 1] for example
    

提交回复
热议问题