using class to calculate average of a list of entry in python

Question:

I have to use the class method in python to calculate the average age, height, and weight of a list of 2 school classes and compare them.

In order to calculate the average ages, I used the following code:

from statistics import mean

class Student():
    counter = 0
    def __init__ (self, age, height, weight):
        Student.counter += 1
        self.age = age
        self.height = height
        self.weight = weight

class Class_a(Student):

    def av_a():
        temp = []
        for i in range (n):
            temp.append(class_a[i].age)
        m_a = (mean(temp))
        return  m_a


class_a = []

n = 2 
age_a = ['15', '99'] 
height_a = ['123', '144'] 
weight_a = ['33', '28']

for i in range (n):
    class_a.append(Class_a(float(age_a[i]), float(height_a[i]), float(weight_a[i])))


print(Class_a.av_a())

It would be highly appreciated if anyone reviews the code and let me know the best way to do such a calculation.

Thank you in advance.

Asked By: Hasan A.

||

Answers:

You could replace Class_a with a kind of collection that would hold multiple Student instances. In this case, no need to inherit from Student:

class Student():
    def __init__(self, age, height, weight):
        self.age = int(age)
        self.height = int(height)
        self.weight = int(weight)

class Students():
    def __init__(self, *students):
        self.students = list(students)

    # implementation of height() and weight() would be similar
    def age(self):
        return mean(map(lambda x: x.age, self.students))

    def add(self, student):
        self.students.append(student)

    def __len__(self):
        return len(self.students)

This way you can initialize with some students:

students = Students(Student('15', '123', '33'))

And/or add more later:

students.add(Student('99', '144', '28'))
students.add(Student('20', '134', '22'))

You have access to the averages at any time:

print(students.age())
Answered By: Ivan
class Student:
    def __init__(self, num, age, heigth, weigth):
        self.number = num
        self.age = age
        self.heigth = heigth
        self.weigth = weigth
    def cal_average(self):
        return(sum(self.age)/len(self.age), sum(self.heigth)/len(self.heigth), sum(self.weigth)/len(self.weigth))

example

a = Student(5,[16, 17, 15, 16, 17],[180, 175, 172, 170, 165],[67, 72, 59, 62, 55])
avg1, avg2, avg3 = a.cal_average()
Answered By: leili akbari
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.