mardi 9 août 2016

Weighted choice in Python

So here is my code:

class ELEMENT:
    def __init__(self, a, b, c, d, e, pref, ranchoices):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.pref = pref
        self.ranchoices = ranchoices

Elements = []

for i in range(20):
    element = ELEMENT(random.randint(0,20), random.randint(0,20), random.randint(0,20), 
    random.randint(0,20), random.randint(0,20), [], [])

    element.pref += int(element.a) * [element.a]
    element.pref += int(element.b) * [element.b]
    element.pref += int(element.c) * [element.c]
    element.pref += int(element.d) * [element.d]
    element.pref += int(element.e) * [element.e]
    Elements.append(element)

for element in Elements:
    for i in range (5):
        ranchoice = random.choice(element.pref)
        element.ranchoices.append(ranchoice)


for element in Elements:
    print "a = " + str(element.a)
    print "b = " + str(element.b)
    print "c = " + str(element.c)
    print "d = " + str(element.d)
    print "e = " + str(element.e)
    for ranchoice in element.ranchoices:
        print ranchoice
    print ""

The idea is to create a list of object with different variables. The program then picks 5 times a variable for each object and add them to a list. The chances of a variable being picked depends on the value of that variable.

The way the program works so far to create that weighted choice is that it adds each variable times their value to a list (so a variable with a value of 10 will be added 10 times to the list) and then picks a random one.

The problem is that the results I get are still too random. Any idea on how to fixe that?




Aucun commentaire:

Enregistrer un commentaire