# How to split a number into 12 random in python and all random number sum to be equal to the number

## Question:

Hello guys i have a problem that that contain any number (eg- 167) will be split into 12 random numbers the sum of the 12 random numbers should be the original number And the numbers be positive, larger than zero, integers

for this i have written a code :

```
a = 167
n = 12
out = diff([0,sort(randperm(a-1,n-1)),a])
```

here i’m getting a error

name ‘diff’ is not defined

Another way:

```
a = 50390
b = rand(10,1)
b = b/sum(b)*a
out=round(b)
out(1) = out(1) - (a-sum(out))
```

Note: this both code is not working so please tell me how to do it

please help me get it..thanks

## Answers:

This should do it.

```
from random import randint
a = 167
n = 12
assert a >= n >= 1
pieces = []
for idx in range(n-1):
# Number between 1 and a
# minus the current total so we don't overshoot
# minus 1 for each number that hasn't been picked
# so they can all be nonzero
pieces.append(randint(1,a-sum(pieces)-n+idx))
pieces.append(a-sum(pieces))
```

Note that these numbers aren’t independent; any time you add a constraint like `THE n VALUES MUST TOTAL a`

, you’re taking away some of the randomness. Here, the numbers later in the distribution are likely to be smaller than the earlier numbers, until the last number which is expected to be average again. If you don’t like that trend, you can `shuffle()`

the resultant list, `pieces`

.

Edit: For floats, you don’t have to save space for the next value (ditto for non-negative int instead of positive int), so it’d look a little different. Basically, you just remove the `-n+idx`

term from the expression, since you no longer need to allocate `n-idx`

more pieces >=1.

```
from random import uniform
a = 166.667
n = 12
assert a > 0
assert n >= 1
pieces = []
for idx in range(n-1):
# Number between 0 and a
# minus the current total so we don't overshoot
pieces.append(uniform(0,a-sum(pieces)))
pieces.append(a-sum(pieces))
```

```
def num_pieces(num,lenght):
ot = list(range(1,lenght+1))[::-1]
all_list = []
for i in range(lenght-1):
n = random.randint(1, num-ot[i])
all_list.append(n)
num -= n
all_list.append(num)
return all_list
num_pieces(167,12)
```