Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
February 12th, 2013, 07:36 PM
 Vanta
Registered User

Join Date: Feb 2013
Posts: 1
Time spent in forums: 6 m 24 sec
Reputation Power: 0
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!

#2
February 12th, 2013, 11:05 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,213
Time spent in forums: 1 Month 3 Weeks 2 Days 18 h 4 m 30 sec
Reputation Power: 455
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!

#3
February 13th, 2013, 01:06 PM
 Dietrich
Contributing User

Join Date: Feb 2005
Posts: 576
Time spent in forums: 5 Days 4 h 53 m 16 sec
Reputation Power: 63
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.
__________________
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

Last edited by Dietrich : February 13th, 2013 at 01:12 PM.

#4
February 13th, 2013, 01:14 PM
 Dietrich
Contributing User

Join Date: Feb 2005
Posts: 576
Time spent in forums: 5 Days 4 h 53 m 16 sec
Reputation Power: 63
@hovh
Start a new thread! Tagging on to an existing unrelated thread is rather rude!

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > A small program to compute averages