Compute the Average

Let A be the average of the numbers in this text file . What is the value of A , rounded to the nearest integer?

Click here to open the file.


The answer is 499.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

The answer is 499 .

Iterate through the list, keeping track of the sum and the total number of integers as you go. When you reach the end of the list, compute the average by dividing the total sum by the number of integers.

Integer Division : When you divide two integers, the result will be rounded down. To preserve the decimal values so you can round correctly, make sure your sum is a non-integer type, such as a float.

Python solution:

# open file in read mode
f = open('cs_avgnums.txt', 'r') 

sum = 0.0 # sum is a float, to avoid integer division
num_ints = 0

# for each line in the file, add to sum and increment num_ints
for line in f: 
    num_ints += 1 
    sum += int(line)
avg = sum / num_ints
print int(round(avg)) 

f.close()

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...