CS 345 Homework 4

Due Monday Feb 13 at 9pm. Upload to Desire 2 Learn dropbox for homework 4.

Python Primer 4: Objects, Files, and Data Solution

Description

For this programming assignment, you are going to design and implement a class that models cars. To test your car class, you will need to open and read a json encoded file containing data about cars. For each json item you will create a Car object with the information in the json object then store the new object in a list. Thus, after reading the file your test program should have an array of “car objects”. Below are the requirements for your Car class as well as your test program.

Requirements for your Car class

  • Your Car class maintains three attributes (year, make, and odometer reading). Attributes must be private: self._year
  • Your Car class must implement the following methods:

    • __init__(self) contructor should take three parameters corresponding to each attribute. Please provide default values.

    • __repr__(self) Returns a string representation of the Car.

    • get_year(self) Returns the year attribute of a car object.

    • get_make(self) Returns the make attribute of a car object.

    • get_odometer(self) Returns the odometer attribute of a car object.

    • get_status(self) Returns “NEW” (odometer < 50K), “USED” (odometer < 150K), or “JUNK” (odometer >= 150K) depending on the odometer value.

Requirements for your Test Program

  1. Open and read in (as json) the file entitled data.txt

Download data.txt

  1. For each json item in the data, create a car object with data points in the object then add the car object to a list.

  2. Once you have loaded your list, implement the following functions:

    a. Determine then print the average odometer reading from all the car objects in the list. Must produce floating point result.

    b. Compute then print the most frequent make in the car data list.

    c. Compute then print the least frequent make in the car data list.

    d. Compute then print the most frequent ocurring status. E.g., “The data contains mostly USED cars.”

What to Turn In?

  • Your single class definition file following the naming conventions required in the syllabus.
  • Your class definition and your test program should be in the same file.

Hints:

  • Reading in a json file will require the use of the json module. Import this at the top of your program. You can then use json.loads(string) to read in a json string and convert it to a python list of dictionary items.
import json

json_data = json.loads(somejsonencodedstringhere)
  • each json object contains information for a single car. You can access this like you would a dictionary:
c = {"status": 99634, "make": "Infiniti", "year": 2012}
print c['status'] # prints 99634
# Example: open a json encoded file for reading, then decode with json.
fp = open('data.txt', 'r')
s = fp.read()
jin = json.loads(s) # this decodes into python data structure

# jin is an actual python list containing dictionaries.
# This can handled with python list processing techniques
for i in jin:
	print i['year']

Solution

# solution.py

import json

class Car(object):
	
	def __init__(self, year=1900, make="model-t", odometer=0):
		self.__year = year
		self.__make = make
		self.__odometer = odometer

	def __repr__(self):
		return ' '.join([str(self.__year), self.__make, str(self.__odometer)])

	def get_year(self):
		return self.__year

	def get_make(self):
		return self.__make

	def get_odometer(self):
		return self.__odometer

	def get_status(self):
		if self.__odometer < 50000:
			return 'NEW'
		if self.__odometer < 150000:
			return 'USED'
		else:
			return 'JUNK'

	""" Not required for assigned homework """
	def serialize_json(self):
		"""Returns a json encodable representation of a Car object."""
		return {'year': self.__year, 'make': self.__make, 'odometer':self.__odometer}

	""" Not required for assigned homework """
	@staticmethod
	def deserialize_json(json_data):
		""" A static method for constructing a Car object from a dictionary object (json generated)"""
		return Car(year=json_data['year'], make=json_data['make'], odometer=json_data['odometer'])


# End of Car class


"""Test Car class methods in 'main' method"""
if __name__=="__main__":

	def get_avg_odometer(carlist):
		if not carlist:
			print 'There appear to be no cars in the list!'
			return

		total = 0
		for car in carlist:
			total += car.get_odometer()
		avg = float(total) / len(carlist)
		print 'Average odometer reading for', len(carlist), 'cars \t ==>', avg

	def get_least_most_makes(carlist):
		if not carlist:
			print 'There appear to be no cars in the list!'
			return

		aggregator = {} # key=make of a car, value=number of occurrences of that make 
		for car in carlist:
			try:
				aggregator[car.get_make()] += 1
			except KeyError:
				aggregator[car.get_make()] = 1

		
		init_key = aggregator.keys()[0] # get first key returned from dictionary
		max_count = (init_key, aggregator[init_key]) # get initial key, value pair as tuple 
		min_count = max_count
		for make, count in aggregator.items():
			if count > max_count[1]:
				max_count = (make, count)
			if count < min_count[1]:
				min_count = (make, count)

		print 'Highest frequency make \t\t\t\t ==>',  max_count[1], max_count[0]
		print 'Lowest  frequency make \t\t\t\t ==>',   min_count[1], min_count[0]

	def get_most_freq_status(carlist):
		if not carlist:
			print 'There appear to be no cars in the list!'
			return

		aggregator = {} # key=status (USED, NEW, or JUNK), value=number of occurrences of that status
		for car in carlist:
			try:
				aggregator[car.get_status()] += 1
			except KeyError:
				aggregator[car.get_status()] = 1

		init_key = aggregator.keys()[0] # get first key returned from dictionary
		max_count = (init_key, aggregator[init_key]) # get initial key, value pair as tuple 
		for status, count in aggregator.items():
			if count > max_count[1]:
				max_count = (status, count)
		
		print 'Cars in list are mostly \t\t\t ==>',  max_count[0], max_count[1], 'junkers'

	def load_data():
		fp = open('data.txt')
		datastr = fp.read() 		# read in the entire data file as a string
		data = json.loads(datastr)  # decode the json string into python data structure
		fp.close()
		
		# comprehension that returns n car objects from each dictionary item in data
		return [Car(year=json_dict['year'], make=json_dict['make'], odometer=json_dict['odometer']) for json_dict in data]
		
		# Alternative comprehension that uses static method for Car class
		# return [Car.deserialize_json(i) for i in data]

	
	"""Run the tests..."""
	print '\n*****************\n'

	carlist = load_data()
	get_avg_odometer(carlist)
	get_least_most_makes(carlist)
	get_most_freq_status(carlist)
	
	print '\n*****************\n'

© 2017 - . All rights reserved
Built using Jekyll