dimanche 8 juillet 2018

making a weighted random state function extensible

I have a weighted random state function which takes a finite numbers of relative weightings and outputs an integer based on a pseudo-random choice. However, I want to make the function extensible to handle n number of weightings. The function currently looks like this:

def weighted_random(weight1, weight2, weight3, weight4, weight5, weight6, weight7, weight8):
totalWeight = weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7 + weight8
randomInt = random.randint(1, totalWeight)

if randomInt <= weight1:
    return 0
elif randomInt > weight1 and randomInt <= (weight1 + weight2):
    return 1
elif randomInt > (weight1 + weight2) and randomInt <= (weight1 + weight2 + weight3):
    return 2
elif randomInt > (weight1 + weight2 + weight3) and randomInt <= (weight1 + weight2 + weight3 + weight4):
    return 3
elif randomInt > (weight1 + weight2 + weight3 + weight4) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5):
    return 4
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5 + weight6):
    return 5
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5 + weight6) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7):
    return 6
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7):
    return 7
else:
    return("error")

What is an elegant way to rewrite this function where it can take *args as input?




Aucun commentaire:

Enregistrer un commentaire