For my CS class I the task given was to take a given Person Class with a name and age attributes.
Then, with an existing list of Person Objects, create a function that returns a tuple of (mean, median, mode) on the given age attribute.
Simple enough, but I wondered if my solution is really all that efficient. I basically iterated a new list of ages from an existing list of Person objects, and that almost feels like there's a better opportunity to optimize a solution...
Wondering if I'm missing something obvious.
from statistics import mean, median, mode
class Person:
def __init__(self, name, age):
"""
initializes a person objects name and age
"""
self._name = name
self._age = age
def get_age(self):
"""
returns the private data member _age
"""
return self._age
def basic_stats(person_list):
"""
creates a list of ages from a list of person objects then calculates
mean, median, and mode from the statistics module
"""
age_list = [i.get_age() for i in person_list]
return (mean(age_list), median(age_list), mode(age_list))