rs19
rs19

Reputation: 667

how do i calculate the average number in a list of number

everything is working except for the last few lines, where i get a typeerror. not sure what datatype needs altering. any ideas? the program is simply rolling two dice and calculating the average number out of 100 rolls.

#two dice roll with average of rolls
import random

total=[]

def roll():
    for i in range(100):
        roll_d=random.randint(1,6), random.randint(1,6) 
        total.append(roll_d)
        print(roll_d)

def main():

    roll()

    s=sum(total)
    average=s/100.0
    print(average)

main()

Upvotes: 1

Views: 1424

Answers (4)

scriptmonster
scriptmonster

Reputation: 2771

There are many ways:

print reduce(lambda x, y: x + y, total)/(len(total)*1.0)

or

sum(total)/(len(total)*1.0)

The 1.0 is to make sure you get a floating point division

or use numpy:

import numpy as np
print np.mean(total)

Upvotes: 1

behzad.nouri
behzad.nouri

Reputation: 77951

as a suggestion, use numpy arrays instead of lists:

import numpy as np
total = np.random.randint( low=1, high=6+1, size=(100,2) ) # 100 by 2 array

total.mean( )        # average of all values   ( 1 number)
total.mean( axis=0 ) # average of each column  ( 2 numbers)
total.mean( axis=1 ) # average of each row     ( 100 numbers)

Upvotes: 1

jon_darkstar
jon_darkstar

Reputation: 16768

As Martin points out, the elements of total are tuples - each of the dice rolls (ex - (3,4), (1,1), etc)

So, if I understand your intentions correctly, you are going to need to add them together as well. You can't sum directly on the tuples.

The following will add each roll together before finding the sum:

s = sum(map(lambda x: x[0]+x[1], total))

And please do not hardcode that 100.0. Use something like s*1.0/len(total)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122082

Each element in total is a tuple of two integers.

You'll have to define how you want these tuples to be summed. Perhaps you wanted to add rolls individually:

def roll():
    for i in range(100):
        roll_d=random.randint(1,6), random.randint(1,6) 
        total.extend(roll_d)
        print(roll_d)

Here total.extend() passed the two rolls individually to the total list. Or perhaps you need to store the sum of the roll:

def roll():
    for i in range(100):
        roll_d=random.randint(1,6), random.randint(1,6) 
        total.append(roll_d[0] + roll_d[1])
        print(roll_d)

If you do want to keep the rolls stored in pairs, you need to adjust your sum() call to sum the individual roll numbers:

s = sum(r for pair in total for r in pair)

Upvotes: 1

Related Questions