Search code examples
pythonsimulatordice

I have dict -> pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0} trying to change the keys' values with for loop, not working,


import random

pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}

for i in range(0, 1001):

    d1 = random.randrange(0, 7)
    d2 = random.randrange(0, 7)
    summ = d1 + d2
    for k, v in pairs.items():
        if summ == k:
            k[v] += 1

Solution

  • What you meant to write was this:

    import random
    
    pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
    
    for i in range(0, 1001):
    
        d1 = random.randint(1, 6)
        d2 = random.randint(1, 6)
        summ = d1 + d2
        pairs[summ] += 1
    
    print(pairs)
    

    I see that you are searching though the pairs dict to find the right key which is a strange way to find a key. I now see the reason for that was because you are using randrange(0, 7) which produces numbers in the inclusive range of 0..6. This will mean that summ could be 0 or 1 which is not one of the keys contained in pairs.

    By using randint(1, 6) this is a lot more like rolling a pair of dice and gives summ in the exact range of the keys you prepared in pairs. This allows my version to just register each roll with pairs[summ] += 1