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

Python: create a complete program that uses classes to store, search, remove, an

ID: 3904987 • Letter: P

Question

Python:  create a complete program that uses classes to store, search, remove, and filter country data. The two major tasks are outlined below

1.? ?Implement a class Country Instance Variables:

i. Name: string

ii. Population: integer

iii. Area: float

iv. Continent: string

Methods:

i. constructor

ii. Getter Methods: getName, getPopulation, getArea, getContinent,

iii. getPopDensity: This calculates and returns the population density for the country. Population density is the population divided by the area.

iv. Setter Methods: setPopulation

v. def ?__repr__(self):generate a string representation for the class Name in Continent

e.g China in Asia class ?Country :

def ?__init__(self, name, pop, area, continent) :

def ?__repr__(self):

def ?setPopulation(self, pop):

def ?getName(self) :

def ?getArea(self) :

def ?getPopulation(self) :

def ?getContinent(self):

def ?getPopDensity(self) :

2. Implement a class called CountryCatalogue This class has two instance variables, catalogue (?that is a set or dictionary or list of countries) and cDictionary? (a dictionary).

This class will have the following methods.

• Constructor:? this method will open the specified files and then first will create the cDictionary and then create countries and add them to catalogue. The constructor is given additional parameters, continentFileName and countryFileName, both strings. Major Steps

1. Fill the Dictionary:? open the file continentFileName and fill cDictionary. The key is the country name, while the continent is the value.

2. Fill the Catalogue:? Open the file countryFileName, then read each line of the file and from that create a country and add it to catalogue.

A sample data file has been included data.txt (Note that both files have headers). Do not forget to close any files that are opened in your methods.

addCountry:? given four parameters countryName (a string), countryPopulation (an integer), countryArea (a float), countryContinent (a string), first create a country using this information. If there is already a country with the same name, return False. Otherwise, there is a new country to add, add the newly created country to catalogue, make sure you add the continent to the cDictionary. Return True after successfully adding the new country. Hint: you may find the keys of cDictionary useful.

deleteCountry:? given a parameter countryName (a string), if there is a country with this name then it should be removed from the country catalogue entirely (both cDictionary and catalogue). Print a message informing the user whether the country has been successfully removed from the country catalogue or not. Do not return anything.

findCountry:? given a parameter countryName (a string), if this country exists then return the country from catalogue. If the country does not exist, return None.

filterCountriesByContinent:? given a parameter continentName (a string), return a list containing all the countries that are on continents that are continentName.

printCountryCatalogue:? print the countries of catalogue to the screen using the default print for the Country Class. This method takes no additional parameters.

setPopulationOfASelectedCountry?: Given two parameters countryName (a string) and countryPopulation (an integer), set the population of the country named countryName (if it is in the catalogue) to the value countryPopulation. Return True if the population is updated, and return False otherwise.

• findCountryWithLargestPop?: find the country with the largest population, return the name of this country. This method takes no additional parameters.

• findCountryWithSmallestArea:? find the country with the smallest area, return the name of this country. This method takes no additional parameters.

• filterCountriesByPopDensity:? given two parameters lowerBound and upperBound (both integers), find all the countries (, i.e. country objects) that have a population density that falls within these two numeric bounds inclusively. Return a list that contains all of these countries.

• findMostPopulousContinent?: find the continent with the most number of people living in it. Return together the name of this continent with its total population. That is, if mostPopCont is the name of the continent found above and popMaxCont is the total population of this continent, use return?(mostPopCont, popMaxCont).

• saveCountryCatalogue:? given a parameter filename (a string), write the country data of the catalogue as specified below to file filename. Each entry should be formatted as below, one country per line. Return the number of lines written to filename.

Format: Name|Continent|Population|PopulationDensity

For example:? China|Asia|1200000000|14.56

class ?CountryCatalogue: def ?__init__(self, continentFileName, countryFileName):

def ?filterCountriesByContinent(self,continentName): def ?printCountryCatalogue(self):

def ?findCountry(self, countryName):

def ?deleteCountry(self, countryName):

def ?addCountry(self, countryName, countryPopulation, countryArea, countryContinent):

def ?setPopulationOfASelectedCountry(self, countryName, countryPopulation):

def ?saveCountryCatalogue(self, filename):

def ?findCountryWithLargestPop(self):

def ?findCountryWithSmallestArea(self):

def ?findMostPopulousContinent(self):

def ?filterCountriesByPopDensity(self, lowerBound, upperBound):

Test your CountryCatalogue class to make sure all functionality is working.

continenet.txt

Country,Continent

China,Asia

United States of America,North America

Brazil,South America

Japan,Asia

Canada,North America

Indonesia,Asia

Nigeria,Africa

Mexico,North America

Egypt,Africa

France,Europe

Italy,Europe

South Africa,Africa

South Korea,Asia

Colombia,South America

data.txt

Country|Population|Area

China|1,339,190,000|9,596,960.00

United States of America|309,975,000|9,629,091.00

Brazil|193,364,000|8,511,965.00

Japan|127,380,000|377,835.00

Canada|34,207,000|9,976,140.00

Indonesia|260,581,100|1,809,590.97

Nigeria|186,987,563|912,134.45

Mexico|128,632,004|1,969,230.76

Egypt|93,383,574|1,000,000.00

France|64,668,129|541,656.76

Italy|59,801,004|300,000.00

South Africa|54,978,907|1,222,222.22

South Korea|50,503,933|98,076.92

Colombia|48,654,392|1,090,909.09

Explanation / Answer

Answer: See the code below:

-----------------------------------------

#program to process country data

#Country class
class Country:
    #instantiation
    def __init(self,name,pop,area,continent):
        self.Name = name
        self.Population = pop
        self.Area = area
        self.Continent = continent
  
    #string representation
    def __rep__(self):
        return '%s in %s' % (self.Name, self.Continent)
  
    #set population
    def setPopulation(self,pop):
        self.Population = pop
      
    #get name
    def getName(self):
        return self.Name
  
    #get area
    def getArea(self):
        return self.Area
  
    #get population
    def getPopulation(self):
        return self.Population
  
    #get Continent
    def getContinent(self):
        return self.Continent
  
    #get population density
    def getPopDensity(self):
        return (self.Population/self.Area)
  

#CountryCatalogue class
class CountryCatalogue:
    #instantiation
    def __init__(self,continentFileName,countryFileName):
        self.catalogue = [] #for catalogue of countries
        self.cDictionary = {} #for dictionary of country and continent
      
        #read continent file line by line
        with open(continentFileName) as file:
            data = file.readlines()
        #strip ' ' at the end of each line
        data = [line.rstrip(' ') for line in data]
        #fill cDictionary
        for line in data:
            #split line
            [count,cont] = line.split(',')
            self.cDictionary[count] = cont
                          
        #read country file name line by line
        with open(countryFileName) as file1:
            data1 = file1.readlines()
        #strip ' ' at the end of each line
        data1 = [line.rstrip(' ') for line in data1]  
        #fill catalogue
        for line in data1:
            #split line
            [count,pop,area]=line.split('|')
            pop=int(pop) #convert pop to integer
            area=float(area) #convert area to float
            cont = self.cDictionary[count]
            country = Country(count,pop,area,cont)
            self.catalogue.append(country)
       #close files
       #file.close()
       #file1.close()
     
    #add country
    def addCountry(self,countryName,countryPopulation,countryArea,countryContinent):
        #create new country
        country = Country(countryName,countryPopulation,countryArea,countryContinent)
        #check if new country already existing in catalogue
        if country.getName in self.cDictionary:
            return False
        else:
            self.catalogue.append(country) #add country to catalogue
            self.cDictionary[country.getName()] = country.getContinent() #add to dictionary
            return True
  
    #delete country
    def deleteCountry(self,countryName):
        #look for country in dictionary. if found, then delete, otherwise not
        if countryName in self.cDictionary:
            self.catalogue = [country for country in self.catalogue if country.getName() != countryName]
            del self.cDictionary[countryName]
            print(countryName," has been removed successfully from country catalogue.")
        else:
            print(countryName," has not been removed from country catalogue.")
  
    #find country
    def findCountry(self,countryName):
        #look for country in dictionary. if found, then return that country, otherwise do nothing
        if countryName in self.cDictionary:
            for country in self.catalogue:
                if country.getName() == countryName:
                    return country
        return "None"
  
    #filter countries by continent
    def filterCountriesByContinent(self,continentName):
        countries=[]
        for country in self.catalogue:
            if country.getContinent() == continentName:
                countries.append(country.getName())
        return countries
  
    #print country catalogue
    def printCountryCatalogue(self):
        for country in self.catalogue:
            print(country)
  
    #set population of a selected country
    def setPopulationOfASelectedCountry(self,countryName,countryPopulation):
        for country in self.catalogue:
            if country.getName() == countryName:
                country.setPopulation(countryPopulation)
                return True
        return False
  
    #find country with largest population
    def findCountryWithLargestPop(self):
        #number of countries
        numCountries = len(self.catalogue)
        #country with largest population
        countryLargestPop = self.catalogue[0] #assume first country in catalogue is as such
        #now search country with largest population
        for i in range(1,numCountries):
            if countryLargestPop.getPopulation() < self.catalogue[i].getPopulation():
                countryLargestPop = self.catalogue[i]
        #return country name with largest population  
        return countryLargestPop.getName()
  
    #find country with smallest area
    def findCountryWithSmallestArea(self):
        #number of countries
        numCountries = len(self.catalogue)
        #country with smallest area
        countrySmallestArea = self.catalogue[0] #assume first country in catalogue is as such
        #now search country with largest population
        for i in range(1,numCountries):
            if countrySmallestArea.getArea() > self.catalogue[i].getArea():
                countrySmallestArea = self.catalogue[i]
        #return country name with largest population  
        return countrySmallestArea.getName()
  
    #filter countries by population density
    def filterCountriesByPopDensity(self,lowerBound, upperBound):
        countries=[]
        for country in self.catalogue:
            if country.getPopDensity() > lowerBound and country.getPopDensity() < upperBound :
                countries.append(country.getName())
        return countries
  
    #find most populous continent
    def findMostPopulousContinent(self):      
        #expand country catalogue
        catalogueData = []
        for country in self.catalogue:
            catalogueData.append((country.getName(),country.getContinent(),country.getArea(),country.getPopulation()))
        catalogueDataLabels=['country','continent','area','population']
        #create a pandas data frame from expanded catalogue
        import pandas as pd
        df = pd.DataFrame.from_records(catalogueData,columns=catalogueDataLabels)
        #group by continent
        dataByContinent = df.groupby('continent')
        import numpy as np
        populationByContinent = dataByContinent['population'].agg(np.sum)
        return populationByContinent.iloc[populationByContinent['population'].argmax()]

----------------------------------------------