Home > Software design >  Python: Average of items in matrix
Python: Average of items in matrix

Time:11-17

We have a code like this at our school as a home assignment. The code need to be done in python 2, because of an school made app:

Write a function average(m), which receives a matrix containing integer items as argument. The function calculates and returns the average of the items in the matrix.

Below is the code given:

def test():
    l = []
    for i in range(random.randint(3,5)):
        ll = []
        for j in range(random.randint(3,4)):
            ll.append(random.randint(1,10))
        l.append(ll)
    print ("Matrix:",l)
    print ("Average of items:", average(l))

test()
print ("")
test()

import random

I tried doing this:

def average(m):

lst = []
average = sum(lst) / len(lst)
 return average

But it comes back with:

TypeError: unsupported operand type(s) for /: 'list' and 'int'

I've tried to find solutions for making lists join another, but I have not been able to make any use of the help that is provided in the web. Appreciate any help that is given, thank you.

CodePudding user response:

Basic manual approach is a nested loop to collect total and count:

def average(m):
    total = count = 0
    for row in m:
        for val in row:
            count  = 1
            total  = val
    return total / count

Of course there are utils to achieve this in fewer lines:

def average(m):
    return sum(map(sum, m)) / sum(map(len, m))

CodePudding user response:

You could use numpy as that works with N dimensional arrays.

The Python built in average function (to date) can only work with one dimensional iterables.

You have to iterate over the rows in your array to sum the columns, e.g.


import random

def test():
    l = []
    for i in range(random.randint(3, 5)):
        ll = []
        for j in range(random.randint(3,4)):
            ll.append(random.randint(1,10))
        l.append(ll)

    return l

def average(ll):
    s = n = 0
    for l in ll:
        s  = sum(l)
        n  = len(l)

    return s/n

res = test()

print ("Matrix:", res)
print ("Average of items:", average(res))

  • Related