SD 212 Spring 2024 / Homeworks


hw27: Temps class

  • Due before the beginning of class on Friday, April 5

The task

A technician collecting temperature data wants to have a Python object to help collect their temperature readings one at a time and get some simple statistics on the list of readings collected so far.

To support this, you will define a class in Python called Temps that supports the following functions:

  • add_reading(x): Adds the number x to the list of temperature readings
  • get_count(): Returns the number of readings added so far
  • get_average(): Returns the average temperature over all readings collected so far
  • get_high(): Returns the highest temperature recorded so far

You will also need an __init__(self) function to create a new Temps object, which takes no arguments.

You can assume that get_average() and get_high() will not be called until after add_reading(x) is called at least once.

(Hint: You might want your __init__ function to create an empty list and save it as an instance variable in the class.)

Your code

Create a file temps.py which contains your class Temp definition and nothing else.

If you want to put any testing code in temps.py outside of your class definition, you should put it under if __name__ == '__main__': so that it does not get executed when your file is imported.

Example

Here is one example of how we will test your class:

from temps import Temps # import the class from your file

hot_day = Temps() # create a new object
print(hot_day.get_count()) # should be 0
hot_day.add_reading(80)
hot_day.add_reading(87)
hot_day.add_reading(92)
hot_day.add_reading(87)
print(hot_day.get_count()) # should be 4
# this should be (80 + 87 + 92 + 87) / 4 = 86.5
print("Average temp on hot day:", hot_day.get_average())
print("High on a hot day:", hot_day.get_high()) # should be 92

# create a different object
cool_day = Temps()
cool_day.add_reading(65)
cool_day.add_reading(75)
# this should print 70.0 and 75
print("Cool day stats:", cool_day.get_average(), cool_day.get_high())

# both objects are independent; should be 4 and 2
print("Number of readings on hot/cool days:", hot_day.get_count(), cool_day.get_count())

Submit command

To submit files for this homework, run one of these commands:

submit -c=sd212 -p=hw27 temps.py
club -csd212 -phw27 temps.py