-3

Given k a random integer between 2 and 7. How to generate a list of k positive numbers whose sum is equal to 1?

Examples of possible expected results:

k = 3 -> list = [0.23, 0.57, 0.2]

k = 3 -> list = [0.41, 0.44, 0.15]

K = 2 -> list = [0.95, 0.5]

crocefisso
  • 793
  • 2
  • 14
  • 29

3 Answers3

4

You can generate k random numbers (for example in the range 0-1), then divide by their sum.

Example with numpy (for efficiency):

k = 3
import numpy as np
a = np.random.random(k)
out = (a/a.sum()).tolist()

pure python:

k = 3
import random
l = [random.random() for _ in range(k)]
s = sum(l)
out = [e/s for e in l]

example: [0.27830153962545046, 0.19826407925979248, 0.523434381114757]

mozway
  • 194,879
  • 13
  • 39
  • 75
1

I hope you are well.

you can use this code to do this:

import numpy as np
def softmax(x):
    res = np.exp(x - np.max(x))
    return res / res.sum()
size=5
list=np.random.random(size)
list=softmax(list)
  • Can you explain the rationale for the `res = np.exp(x - np.max(x))` line? What make the sum equal to 1 is the last line `return res / res.sum()` – mozway Jun 11 '22 at 20:02
  • it's also work for the list of number, which all their value is not positive. it's a very famous math function and widely use in the field of deep learning and machine learning, this function in general called (Softmax), You can read more about it in the wiki : https://en.wikipedia.org/wiki/Softmax_function and if you need more help, please let me now. – Hossein Biniazian Jun 11 '22 at 21:08
1

Using a infinite loop which break once get all k numbers. Repeated numbers may occurs.

import random

#random.seed(3) # for testing purposes

k = 5

partition_of_unit = []
while True:
    if len(partition_of_unit) == k-1:
        break
    n = random.random()
    if sum(partition_of_unit) + n < 1:
        partition_of_unit.append(n)
partition_of_unit.append(1-sum(partition_of_unit))

print(partition_of_unit)
#[0.6229016948897019, 0.029005228283614737, 0.11320596465314436, 0.013114189588902203, 0.22177292258463677]
print(sum(partition_of_unit))
#1.0
cards
  • 3,936
  • 1
  • 7
  • 25