Home

Programming skills : Python ✍️

C++
Java
Python
JavaScript
Python:Print Summary Statistics
import math
UNITS = {
0: ("Celsius", "C"),
1: ("Fahrenheit", "F"),
2: ("Kelvin", "K"),
}
current_unit = 0
class TempDataset:
""" provide methods to access temperature data """
number_of_dataset_objects = 0
MINLENGTH = 3
MAXLENGTH = 20
def __init__(self):
""" initialize instance variables """
self._data_set = None
self._name = "Unnamed"
TempDataset.number_of_dataset_objects += 1
@property
def name(self):
""" return the name of our dataset """
return self._name
@name.setter
def name(self, new_name):
""" validate and store a new dataset name """
if (len(new_name) < TempDataset.MINLENGTH
or len(new_name) > TempDataset.MAXLENGTH):
raise ValueError
self._name = new_name
def process_file(self, filename):
""" load temperature data from a file """
try:
datafile = open(filename, 'r')
except IOError:
return False
self._data_set = []
for line in datafile:
day, time, sensor, readtype, temp = line.split(",")
time = math.floor(float(time) * 24)
if readtype == "TEMP":
self._data_set.append((int(day), time, int(sensor), float(temp)))
datafile.close()
return True
def get_summary_statistics(self, active_sensors):
""" provide min, max and average temperatures of active sensors """
if self._data_set is None:
return None
temps = [elem[3] for elem in self._data_set
if elem[2] in active_sensors]
if len(temps) == 0:
return None
return min(temps), max(temps), sum(temps)/len(temps)
def get_avg_temperature_day_time(self, active_sensors, day, time):
""" provide average temperature for a given day of week and time """
if self._data_set is None:
return None
temps = [elem[3] for elem in self._data_set if elem[0] == day and
elem[1] == time and elem[2] in active_sensors]
if len(temps) == 0:
return None
return sum(temps)/len(temps)
def get_num_temps(self, active_sensors, lower_bound=None, upper_bound=None):
""" provide the number of instances where active sensor temperature
readings are within a given range
"""
if self.data_set is None:
return None
return 0
def get_loaded_temps(self):
""" provide the total number of loaded temperature readings for this
dataset
"""
if self._data_set is None:
return None
return len(self._data_set)
@classmethod
def get_num_objects(cls):
""" provide the number of TempDataset objects that have been created"""
return cls.number_of_dataset_objects
def print_header():
""" print an opening message """
print("STEM Center Temperature Project")
print("Chris Griffen")
def recursive_sort(list_to_sort, key=0):
""" sort a list of tuples on the given key """
length = len(list_to_sort)
if length <= 1:
return list_to_sort
swaplist = list_to_sort.copy()
for i in range(0, length - 1):
if swaplist[i][key] > swaplist[i + 1][key]:
(swaplist[i], swaplist[i + 1]) = \
(swaplist[i + 1], swaplist[i])
return recursive_sort(swaplist[0:length - 1], key) \ + swaplist[length - 1:length]
def new_file(dataset):
""" prompt user for filename and load new temperature file """
filename = input("Please enter the filename of the new dataset: ")
if dataset.process_file(filename):
print("Loaded", dataset.get_loaded_temps(), "samples")
while True:
dataset_name = input("Please provide a 3 to 20 character "
"name for the dataset ")
try:
dataset.name = dataset_name
break
except ValueError:
print("That name is not valid")
else:
print("Unable to load the file")
def choose_units():
""" allow the use to specify the units presented """
global current_unit
print("Current units in", UNITS[current_unit][0])
while True:
print("Choose new units:")
for k, v in UNITS.items():
print(k, "-", v[0])
print("Which unit?")
try:
choice = int(input())
if choice in UNITS:
current_unit = choice
return
print("Please choose a unit from the list")
except ValueError:
print("*** Please enter a number only ***")
def print_filter(sensor_list, active_sensors):
""" print the list of sensors, noting those that are active """
for sensor in sensor_list:
print(sensor[0], sensor[1], sep=': ', end='')
print(' [ACTIVE]') if sensor[2] in active_sensors else print('')
def change_filter(sensor_list, active_sensors):
""" allow the user to modify which sensors are active """
sensors = {sensor[0]: sensor[2] for sensor in sensor_list}
while True:
print()
print_filter(sensor_list, active_sensors)
print()
print(f"Type the sensor number to toggle (e.g. {sensor_list[0][0]}) " f"or x to end", end=' ')
choice = input()
if choice == "x":
break
if choice in sensors:
if sensors[choice] in active_sensors:
active_sensors.remove(sensors[choice])
else:
active_sensors.append(sensors[choice])
else:
print("Invalid Sensor")
def print_summary_statistics(dataset, active_sensors):
""" print the min, max and average temperature based on active_sensors """
stats = dataset.get_summary_statistics(active_sensors)
if stats is None:
print("Please load data file and make sure at least one"
+ " sensor is active")
return
print("Summary statistics for", dataset.name)
print(f"Minimum Temperature: {convert_units(stats[0], current_unit):0.2f} "
f"{UNITS[current_unit][1]}")
print(f"Maximum Temperature: {convert_units(stats[1], current_unit):0.2f} "
f"{UNITS[current_unit][1]}")
print(f"Average Temperature: {convert_units(stats[2], current_unit):0.2f} "
f"{UNITS[current_unit][1]}")
def print_temp_by_day_time(dataset, active_sensors):
print("Print Temp by Day/Time Function Called")
def print_histogram(dataset, active_sensors):
print("Print Histogram Function Called")
def print_menu():
""" Print the main menu """
print()
print("Main Menu")
print("---------")
print("1 - Process a new data file")
print("2 - Choose units")
print("3 - Edit room filter")
print("4 - Show summary statistics")
print("5 - Show temperature by date and time")
print("6 - Show histogram of temperatures")
print("7 - Quit")
print()
def convert_units(celsius_value, units):
""" convert celsius to celsius, Fahrenheit or Kelvin """
if units == 0:
return celsius_value
if units == 1:
return celsius_value * 1.8 + 32
return celsius_value + 273.15
def main():
current_set = TempDataset()
sensor_list = [ ("4213", "STEM Center", 0), ("4201", "Foundations Lab", 1), ("4204", "CS Lab", 2), ("4218", "Workshop Room", 3), ("4205", "Tiled Room", 4), ("Out", "Outside", 10)]
active_sensors = [sensor[2] for sensor in sensor_list]
sensor_list = recursive_sort(sensor_list, 0)
print_header()
while True:
print_menu()
print(current_set.get_avg_temperature_day_time(active_sensors, 5, 7))
try:
choice = int(input("What is your choice? "))
except ValueError:
print("*** Please enter a number only ***")
else:
if choice == 1:
new_file(current_set)
elif choice == 2:
choose_units()
elif choice == 3:
change_filter(sensor_list, active_sensors)
elif choice == 4:
print_summary_statistics(current_set, active_sensors)
elif choice == 5:
print_temp_by_day_time(current_set, active_sensors)
elif choice == 6:
print_histogram(current_set, active_sensors)
elif choice == 7:
print("Thank you for using the STEM Center Temperature Project")
break
else:
print("Invalid Choice")
if __name__ == "__main__":
main()
counter free