1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Rep Power

    A Quick Average Function

    Hello forum members!

    I'm new to Python and new to these forums, but looking forward to learning from you all.

    I've got a problem I'm seeking some help with answering... and the problem is:

    Implement function avg() that takes as input a list that contains lists of numbers. Each number list represents the grades a particular student received for a course. For example, here is an input list for a class of four students: [[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]

    The function avg should print, one per line, every student's average grade. You may assume that every list of grades is nonempty, but you may not assume that every student has the same number of grades.

    Your help is much appreciated! I'm not looking for someone to answer the question for me, just some guidance as far as where to begin... Thanks.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Rep Power
    I know this is for class and I probably shouldn't answer this, but what your teacher doesn't know won't hurt them!

    This is a pretty simple function.

    def avg(grades):
    	for student in grades:
    		for grade in student: avg+=grade
    		print avg/len(student)
    As you can see, it goes through all the items in the "grades" input list. Each student has his or her own list of grades, so you make an average out of that.

    I'm sure there's an even shorter way to do this.
  4. #3
  5. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    It won't help to tell you this project exhibits poor design, so I won't point out that a more likely generally useful averaging function would take a list of numbers and return its average. This avg function is munged with the requirement accept a list of lists and print something. As eliskan said, this is simple and hard to advise without supplying the whole code. I considered providing a doctest, 90 60 87 11 being the rounded results of your sample data, but it would preclude you from clever output such as
    student  average
    1        90
    2        60
    3        87
    4        11
    OK, there's a challenge for you. Modify eliskan's code to create this pretty output.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo