Search code examples
pythondice

How to call the random list function without chaning it in Python?


I really need help. I defined a function that gives a x number of rolls for n-sided dice. Now I am asked to calculate the frequency of the each side and freq1 += 1 doesn't seem to work considering there can be many more sides (not just 6) and what I did was;

the first function I defined was dice(x),

freq_list = list(range(1,(n+1)))
rollfreq = [0]*n
for w in dice(x):
    rollfreq[w-1] += 1

print zip(freq_list,rollfreq)

I get a list such as [(1,0),(2,4),(3,1)...] so on, which is expected, yet the problem is the rollfreq valus doesn't match the original randomly generated dice(x) list. I assume it is because since it is RNG, it changes the values of the dice(x) in the second run as well so that I can not refer to my original randomly generated dice(x) function. Is there any solution to this? I mean I tried almost everything, yet it apparently doesn't work!

EDIT:

import random

n = raw_input('Number of the sides of the dice: ')
n = int(n)
x = raw_input('Number of the rolls: ')
x = int(x)

def dice():
    rolls = []
    for i in range(x):
        rolls.append(random.randrange(1, (n+1)))
    return rolls
print dice()
freq_list = list(range(1,(n+1)))
rollfreq = [0]*n
for w in dice():
        rollfreq[w-1] += 1

print 'The number of frequency of each side:', zip(freq_list,rollfreq)

I have added the code - hope you guys can help me figure it out this, thank you!


Solution

  • You called the dice() function twice, once when you printed it, and once when you iterated through it in a for loop. The different results come from there.

    import random
    
    n = raw_input('Number of the sides of the dice: ')
    n = int(n)
    x = raw_input('Number of the rolls: ')
    x = int(x)
    
    def dice():
        rolls = []
        for i in range(x):
            rolls.append(random.randrange(1, (n+1)))
        return rolls
    
    freq_list = list(range(1,(n+1)))
    rollfreq = [0]*n
    
    # Grab the rolls
    rolls = dice()
    # Print them here
    print(rolls)
    
    for w in rolls:
            rollfreq[w-1] += 1
    
    print 'The number of frequency of each side:', zip(freq_list,rollfreq)