1

I have this problem on my study guide that calls for a function that gets the average of two dimensional lists and prints them as one list. I don't really have experience messing with two dimensional lists therefore have no clue where to even begin attacking this problem.

example of what it should do:

avrg([[85, 23, 45], [66, 75, 54], [85, 54, 70], [34, 10, 0]])

[51.0, 65.0, 162.333333333334, 14.66666666666667]

my coding:

def avrg(L):
    for i in range(len(L)):
        for j in range(len(L[0])):
            L[i][j] / i

    return L

Where in my coding did I go wrong?

4 Answers 4

1

For a start, the expression x / y results in a value but does not change x or y. If you're using Python, you might also want to think about using the actual list contents in the iteration instead of the more C-like "range" and accessors. Hopefully this should give you a strong push in the right direction to go:

def avrg( inlist ):
    result = []
    for a in inlist:
        # now "a" is just a list by itself
        n = len(a)
        total = sum(a)
        # you can fill in the rest here
    return result
Sign up to request clarification or add additional context in comments.

Comments

1

The 1st, 2nd, and 4th numbers are the average of the 1st, 2nd, and 4th lists, but the 3rd is not. I'll assume that's a typo, and you meant '69.666...'.

You went wrong in the 'L[i][j] / i' bit. You can think of that statement as computing a value, and then dropping it; you don't assign it to anything. You might want to return a new list as well, perhaps, rather than putting values into the parameter. Also, you went wrong in the looping and indexing, and not actually calculating an average. Also, you went wrong in the j loop: what if some list has more values than another one? Also, you went 'wrong' by not making it pythonic and looping over the list with range and indexing, rather than looping over the items themselves ('for sublist in L: ...'). Also, you went 'wrong' by not using list comprehensions.

This is what I would have done:

def avrg(L):
   return [sum(sublist) / len(sublist) for sublist in L]

print(avrg([[85, 23, 45], [66, 75, 54], [85, 54, 70], [34, 10, 0]])

1 Comment

Thank you the explanation of what was wrong with my coding, it REALLY helped me out.
0

There is no summing. You have to add the elements in each row, and then divide by the length (3 in this case).

Comments

0
import numpy as np
def avrg(ls):
    return map(np.average, ls)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.