How to handle a set of objects in Python


#1

I am desperately trying to figure out how to handle this problem. Any help with the coding is appreciated.


Problem with python objects
#2

A fair point is made at stackoverflow, although be it a bit harsh

python has a csv library, which you can just important and use. Why reinvent the wheel? Can’t you use it because you are restricted in the assignment?


#3

I am given the following data-file:

stars.csv

Peter Piper,23,89.4,1.82
Polly Perkins,47,148.8,1.67
Griselda Gribble,92,48,1.45
Ivan Ng,19,59,2.0
Lucy Lovelorn,14,50,1.6
Leslie McWhatsit,70,59.2,1.65

I have been given a class definition (and some methods) and was asked to add some functions. This I did as shown:

class Person:
    """Defines a Person class """
    def __init__(self, name, age, weight, height):
        """ Create a new Person object"""
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height

    def bmi(self):
        """ Return the body mass index of the person """
        return self.weight / (self.height * self.height)

    def status(self):
        """  status """
        bmi = self.bmi()
        if bmi < 18.5:
            status = "Underweight"
        elif 18.5 <= bmi < 25:
            status = "Normal"
        elif 25 <= bmi < 30:
            status = "Overweight"
        elif bmi >= 30:
            status = "Obese"
        return status

    def __str__(self):
        """ Output data """
        answer = "{0} ({1}) has a bmi of {2:.02f}. Their status is {3}."
        return answer.format(self.name, self.age, self.bmi(), self.status())

def read_stars(csv_filename):
    """reads file and sorts it then runs through a class"""
    items = []
    file = open(csv_filename, 'r')
    for row in file:
        name, age, weight, height = row.split(',')
        items.append(Person(name, int(age), float(weight), float(height)))
    file.close()
    return items

Then I need to a create a new function filter_people(people, status) that takes a list of people and a “status” string and returns a new list containing just the people from the original list whose health status equals the status parameter. So far, so good. So, where am I stuck? In manipulating the filter_stars GLOBAL function. Is it possible to create a global function filter_stars(people, status) such that the output will be classified based on their bmi and status?

Test code

bods = read_stars("stars.csv")
for status in ['Underweight', 'Normal', 'Overweight', 'Obese']:
    bods_with_status = filter_stars(bods, status)
    print("People who are {}:".format(status))
    for bod in bods_with_status:
        print(bod)
    print()

Expected Output

People who are Underweight:
Ivan Ng (19) has a bmi of 14.75. Their status is Underweight.

People who are Normal:
Griselda Gribble (92) has a bmi of 22.83. Their status is Normal.
Lucy Lovelorn (14) has a bmi of 19.53. Their status is Normal.
Leslie McWhatsit (70) has a bmi of 21.74. Their status is Normal.

People who are Overweight:
Peter Piper (23) has a bmi of 26.99. Their status is Overweight.

People who are Obese:
Polly Perkins (47) has a bmi of 53.35. Their status is Obese.

I am totally stuck as to come up with a function that can output as above. Please help with writing the global function filter_stars(people, status)

Help appreciated.


#4

Yes, the assignment restricts me from doing so. :frowning:

Can you please help. My mind has gone blank.


#5

I will have a look, but i would recommend you to include details like that (not allowed to use certain libraries) in the question.

i think you are actually pretty far. This will give you all the different horses:

bods = read_stars("stars.csv")

bods is a list, if you loop over the list and print each bod, the string representation is used, so you should be all good


#6
  1. From now on I shall definitely emphasize if there are any specific restraints.
  2. Yes, I was able to figure out the reaed_stars(“stars.csv”)
  3. The headache is with figuring out what goes into the global function filter_stars(stars, status) as I have mentioned at the end of my description above.
  4. Thank you for willing to take a look at the problem. I appreciate it.

#7

i borrow from stackoverflow:

Not sure what the problem is. It takes 10 seconds to google how to filter a list

I think that is a good first step, just pick one of the weights, for example underweight and see if you can filter all the horses with that weight.


#8

Here’s the primary problem. When I type in the whole code, I am not getting any outputs. It is as if the read_stars is not working.

class Person:
    """Defines a Person class """
    def __init__(self, name, age, weight, height):
        """ Create a new Person object"""
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height

    def bmi(self):
        """ Return the body mass index of the person """
        return self.weight / (self.height * self.height)

    def status(self):
        """  status """
        bmi = self.bmi()
        if bmi < 18.5:
            status = "Underweight"
        elif 18.5 <= bmi < 25:
            status = "Normal"
        elif 25 <= bmi < 30:
            status = "Overweight"
        elif bmi >= 30:
            status = "Obese"
        return status

    def __str__(self):
        """ Output data """
        answer = "{0} ({1}) has a bmi of {2:.02f}. Their status is {3}."
        return answer.format(self.name, self.age, self.bmi(), self.status())

def read_stars(csv_filename):
    """reads file and sorts it then runs through a class"""
    items = []
    file = open(csv_filename, 'r')
    for row in file:
        name, age, weight, height = row.split(',')
        items.append(Person(name, int(age), float(weight), float(height)))
    file.close()
    return items

Test Code:

for bod in bods:
    print(bod)

Expected Output:

Peter Piper (23) has a bmi of 26.99. Their status is Overweight.
Polly Perkins (47) has a bmi of 53.35. Their status is Obese.
Griselda Gribble (92) has a bmi of 22.83. Their status is Normal.
Ivan Ng (19) has a bmi of 14.75. Their status is Underweight.
Lucy Lovelorn (14) has a bmi of 19.53. Their status is Normal.
Leslie McWhatsit (70) has a bmi of 21.74. Their status is Normal.

But when I compile the program, I get nothing. I get an empty list as output.


#9

i ran your code here:

https://repl.it/@stetim94/InsubstantialUglyBlackpanther

i do not get an empty list. Its the same code as yours, assuming you called read_stars function correctly


#10

That’s weird. I tried it at the link you provided. It is working. Let me cross-check my code indentation. Thanks a lot for the link. I will update


#11

I tried and tried. Not able to figure out how to deal with the nested loop. Can you please share the function filter_stars(stars, status)?


#12

i can’t, i haven’t written the function. Furthermore, i spend a long time learning programming. And i like helping people (for free), but writing solutions is what a developers get paid for, so that for me is where the line is.

but feel free to share your attempt(s), so i can help you