February 12th, 2013, 06:36 PM

A small program to compute averages
I am currently taking a python programming class and we are working on a program that requires finding averages of some values from an imported file, but I am having some issues creating a while or for loop that can compute averages.
Lets say I have a list newlist = [1, 2, 3, 4, 5]
I want to create a loop that will compute the mean of these values, which of course is 3. I know I will need a few variables but I do not know how to utilize them. Of course, I will need to convert the values in newlist to integers as well.
Does anyone know how to do something like this with basic syntax? Of course we have covered conditionals, while loops, for loops, string methods, booleans, etc, but I just cannot seem to make a program that will find the average and print it out.
Some help would be appreciated!
Thanks!
February 12th, 2013, 10:05 PM

If you knew both the sum of the items in the list and its length you could solve the problem. Something like
average = sum(LIST) / len(LIST)
print(average)
sum and len are python functions, you don't need to write them.
>>> LIST = [1,2,3,4,5]
>>> average = sum(LIST) / len(LIST)
>>> print(average)
3
Wow! It works. Let's try again.
Code:
>>> A = [3, 4]
>>> print(sum(A) / len(A)) # trouble
3
>>> import fractions
>>> print(fractions.Fraction(sum(A), len(A)))
7/2
>>> print(sum(A) / float(len(A))) # resolution
3.5
>>>
[code]
Code tags[/code] are essential for python code and Makefiles!
February 13th, 2013, 12:06 PM

FYI ...
In Python2 x / y means integer division if numbers x and y are integers
You can change that to floating point division by making at least one of the numbers a float
In Python3 x / y means floating point division and x // y means integer division. It doesn't matter if x or y are integers or floats.
Last edited by Dietrich; February 13th, 2013 at 12:12 PM.
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
February 13th, 2013, 12:14 PM

@hovh
Start a new thread! Tagging on to an existing unrelated thread is rather rude!
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25