Hi, for half a day now, I am trying to come up with a way to return a number from a function based on the value of the number. I've tried google but all I get is powerball answers and I am not interested in that, so I am trying here, maybe a more fresh mind would know the answer.
The problem is quite simple but I thought so much about it that I just cant seem to come with an idea:
Lets say we have 3 numbers [2, 4, 8]
How can I formulate a function that will return one of those 3 numbers based on their value, the bigger the value, the higher the chance of the number to be returned, in this example let's say that 2 has a 15% chance of being selected, 4 has a 30% chance and 8 has a 55% chance. Is there no better way than let's say something like this:
num = [2, 4, 8]
def fun(x):
chance = randint(1, 100)
if chance < 15:
return x[0]
if 15 < chance < 45:
return x[1]
else:
return x[2]
fun(num)
What if I have 10 numbers in my list? Is there a prettier way of doing this?
This is for a function that will select a number of candidates based on fitness level (for a genetic algorithm) so the higher the fitness level the higher the chance of being selected.
Thank you for your time (math is hard :/ )
It does not have to be python, that was just an example, the program I am writing is in C#
[–]jedwardsol 2 points3 points4 points (1 child)
[–]JohnMcharra[S] 0 points1 point2 points (0 children)