user3036719
user3036719

Reputation: 5

Python-random number and its frequency

The function randint from the random module can be used to produce random numbers. A call on random.randint(1, 6), for example, will produce the values 1 to 6 with equal probability. Write a program that loops 1000 times. On each iteration it makes two calls on randint to simulate rolling a pair of dice. Compute the sum of the two dice, and record the number of times each value appears.

The output should be two columns. One displays all the sums (i.e. from 2 to 12) and the other displays the sums' respective frequencies in 1000 times.

My code is shown below:

import random
freq=[0]*13

for i in range(1000):
    Sum=random.randint(1,6)+random.randint(1,6)
    #compute the sum of two random numbers
    freq[sum]+=1
    #add on the frequency of a particular sum

for Sum in xrange(2,13):
    print Sum, freq[Sum]
    #Print a column of sums and a column of their frequencies

However, I didn't manage to get any results.

Upvotes: 0

Views: 3776

Answers (4)

Shwe Yee
Shwe Yee

Reputation: 1

import random
frequency_dict={}
for i in range(100):
    number=random.randint(1,10)
    if number in frequency_dict:
        frequency_dict[number] +=1
    else:
        frequency_dict[number] =1
    for key in frequency_dict:
        print(f'{"Number":<10}',f'{"Frequency":<10}')
        print(f'{key:<10}',f'{frequency_dict[key]:<10}')
        

Upvotes: 0

Alfe
Alfe

Reputation: 59416

You shouldn't use Sum because simple variables should not be capitalized.

You shouldn't use sum because that would shadow the built-in sum().

Use a different non-capitalized variable name. I suggest diceSum; that's also stating a bit about the context, the idea behind your program etc. so a reader understands it faster.

You don't want to make any readers of your code happy? Think again. You asked for help here ;-)

Upvotes: 1

Kannan Mohan
Kannan Mohan

Reputation: 1840

Looks like a typo error. Sum variable is wrongly typed as sum.

Below is the modified code in python 3.x

#!/usr/bin/env python3

import random

freq= [0]*13

for i in range(1000):
    #compute the sum of two random numbers
    Sum = random.randint(1,6)+random.randint(1,6)

    #add on the frequency of a particular sum
    freq[Sum] += 1

for Sum in range(2,13):
    #Print a column of sums and a column of their frequencies
    print(Sum, freq[Sum])

Upvotes: 0

Marco A.
Marco A.

Reputation: 43662

Try this:

import random
freq=[0]*13

for i in range(1000):
  Sum=random.randint(1,6)+random.randint(1,6)
   #compute the sum of two random numbers
  freq[Sum]+=1
  #add on the frequency of a particular sum

for Sum in xrange(2,13):
  print Sum, freq[Sum]
  #Print a column of sums and a column of their frequencies

There's a grammar case error on sum

The seed generator that python uses should suffice to your task.

Upvotes: 0

Related Questions