Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Write a class MyClass which has one data member data which is a dictionar

ID: 3830935 • Letter: P

Question

Python

Write a class MyClass which has one data member data which is a dictionary. Create a function loadwhich takes in a filename and reads the lines to load elements in the dictionary and returns the number of lines read. Each line of the file contains item name and number of items separated by a vertical bar ('|') character. Each element in the dictionary is a key-value pair: name (string) and count (int). You must parse each line to store in the dictionary and if the value is invalid do not add it to the dictionary. You must handle when the file does not exist and return -1. (Hint: use try-except for exception handling, also make sure key values are stripped off white spaces). Write another function find which takes in an integer "num" and returns a list of keys from the dictionary which have the value same as num.

Explanation / Answer

code:

import os
import sys
import numpy as np

class MyClass:
   def __init__(self):
       self.mapped = {}
   def load(self,filename):
       fr = open(filename,"r")
       lines =fr.readlines()
       for line in lines:
           key_values = line.split()
           self.mapped[int(key_values[0])] = len(key_values[1].strip().split("|"))
       return len(lines)
  
   def find(self,num):
       result=[]
       for key,value in self.mapped.iteritems():
           if value==num:
               result.append(key)
       return result
      

obj = MyClass()                      
print obj.load("input.txt")
print obj.find(3)