vendredi 29 juillet 2022

How do you create 3 random numbers that add up to a specific number in python [duplicate]

I'm trying to create a code that will generate 'x' numbers that all add up to 'y'. For example, 3 numbers that add up to 100: 25, 25, 50. I am having trouble even finding a way to write an example code so this is the best I've got.

import random

finalnum = 100
sum = 0

num1 = random.randint(0, finalnum)
sum += num1

num2 = random.randint(0, finalnum - num1)
sum += num2

num3 = finalnum - sum
sum += num3

print(num1, '+', num2, '+', num3, '=', sum)

There are a number of issues with this example. The biggest is that you can't choose how many numbers add up to the final number, and the next issue is that it is totally imbalanced. The first randomized number is usually the biggest number. I want each of the numbers to have a truly random chance to be the biggest if that is possible. Thanks!




Aucun commentaire:

Enregistrer un commentaire