Question

I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...

I NEED TASK 3 ONLY

TASK 1

country.py

class Country:

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

        self.name = name

        self.pop = pop

        self.area = area

        self.continent = continent

    def getName(self):

        return self.name

    def getPopulation(self):

        return self.pop

    def getArea(self):

        return self.area

    def getContinent(self):

        return self.continent

    def setPopulation(self, pop):

        self.pop = pop

    def setArea(self, area):

        self.area = area

    def setContinent(self, continent):

        self.continent = continent

    def __repr__(self):

        return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ')

TASK 2

Python Program:

File: catalogue.py

from Country import Country

class CountryCatalogue:
   def __init__(self, countryFile):
       """ Constructor that creates the Country List using file """
       # List that holds country info
       self.countryCat = []
       # Opening file
       fp = open(countryFile, "r")
       # ignoring first line
       header = fp.readline()
       # Iterating over file
       for line in fp:
           # Stripping new line
           line = line.strip()
           # Splitting on |
           data = line.split('|')
           # Creating country object
           cObj = Country(data[0], data[2], data[3], data[1])
           # Adding to list
           self.countryCat.append(cObj)
       # Closing file
       fp.close()
   def setPopulationOfCountry(self, country, population):
       """ Setter Methods """
       # Iterating over Countries
       for i in range(len(self.countryCat)):
           if self.countryCat[i].getName() == country.getName():
               # Updating values
               self.countryCat[i].setPopulation(population)
               print("\nUpdated Successfully...\n")
   def setAreaOfCountry(self, country, area):
       """ Setter Methods """
       # Iterating over Countries
       for i in range(len(self.countryCat)):
           if self.countryCat[i].getName() == country.getName():
               # Updating values
               self.countryCat[i].setArea(area)
               print("\nUpdated Successfully...\n")

   def setContinentOfCountry(self, country, continent):
       """ Setter Methods """
       # Iterating over Countries
       for i in range(len(self.countryCat)):
           if self.countryCat[i].getName() == country.getName():
               # Updating values
               self.countryCat[i].setContinent(continent)
               print("\nUpdated Successfully...\n")          
   def findCountry(self,country):
       """ Finds a country """
       # Iterating over Countries
       for cObj in self.countryCat:
           if cObj.getName() == country.getName():
               return country
       return None
     def addCountry(self,countryName,pop,area,cont):
       """ Adds a country """
       found = False
       # Iterating over Countries
       for i in range(len(self.countryCat)):
           if self.countryCat[i].getName() == countryName:
               found = True
       if found:
           return False
       else:
           # Adding country
           cObj = Country(countryName, pop, area, cont)
           self.countryCat.append(cObj)
           return True
   def printCountryCatalogue(self):
       """ Prints country Catalogue """
       for cObj in self.countryCat:
           print(repr(cObj)

def saveCountryCatalogue(self,fname):
       """ Saves information to file """
       # Sorting the list
       for i in range(len(self.countryCat)):
           for j in range(i):
               if self.countryCat[i].getName() < self.countryCat[j].getName():
                   temp = self.countryCat[i]
                   self.countryCat[i] = self.countryCat[j]
                   self.countryCat[j] = temp;
              
       # Opening & Writing to file
       fp = open(fname, "w")
      
       fp.write("Country|Continent|Population|Area\n")
      
       # Iterating over objects
       for cObj in self.countryCat:
           fp.write(cObj.getName() + "|" + cObj.getContinent() + "|" + cObj.getPopulation() + "|" + cObj.getArea() + "\n")
          
       # Closing file
       fp.close();
                      

File: CountryCatalogue.py

from catalogue import CountryCatalogue
from Country import Country

def main():
   """ Main function """
   # Creating object
   ccObj = CountryCatalogue("d:\\Python\\countries.txt")
  
   print("Data in file: \n")
  
   # Printing values
   ccObj.printCountryCatalogue()

   # Adding country
   ccObj.addCountry("DEF", "234,658,99", "56,859", "Africa")

   print("\n\nAfter adding new country: \n")
  
   # Printing values
   ccObj.printCountryCatalogue()
  
   # Saving to file
   ccObj.saveCountryCatalogue("d:\\Python\\newcountries.txt")
  
# Calling main
main()  

______
TASK 3
Implement a Python module, called processUpdates.py, that has a function
processUpdates(cntryFileName,updateFileName). This function takes two parameters: the first
parameter will be the name of a file containing country data (e.g. data.txt). The second file will
contain the name of a file containing updates. Each record in the update file specifies updates for a
single country. The format of a record is as follows:
Country;update1;update2;update3
Where an “update” is of the form “L=value” and L can be P, for population, A for area and C for
continent. Updates are separated by semicolons and a line can have 0, 1, 2 or 3 updates; any updates
beyond 3 are simply ignored.
An example of an update file is:
Brazil;P=193,364,111;A=8,511,966
Indonesia;P=260,581,345
Japan;P=127,380,555;A=377,800
Sweden;P=9,995,345;A=450,295;C=Europe
Italy; P=59,801,999
Canada;C=North America
Egypt;A=1,000,000 ; P=93,384,001
Notice that:
 The updates can be in different orders, e.g. the updates for Egypt are area first, then
population.
 If a country is specified and that country is NOT already in the catalogue then that country
and its attributes (at least the ones specified; not all have to be specified) should be
added to the catalogue.
 There can be spaces around the semicolons; spaces in other places may cause errors and
should be handled as exceptions (see below).
The function processUpdates gets two files as parameters. The first parameter is the name of the file
with the country data and the second parameter is the name of file with the update data.
The country file should be processed first. The function processUpdates should ensure that it exists.
If it does exist, it should then proceed to process the data file using the class CountryCatalogue. If the
country file does not exist, then processUpdates should give the user the option to quit or not
(prompts for “Y” (yes) or “N” (no)). If the user does not wish to quite (responds with “N”), then the
function should prompt the user for the name of a new file. If the user wishes to quit (responds with
a “Y” or anything other than a “N”, then the method should exit and return False. The method should
continue to prompt for file names until a valid file is found or the user quits.
If the user chooses to quit, i.e. no country file is processed, then the function processUpdates should
NOT try to process the updates file, write to the file “output.txt” the message "Update
Unsuccessful\n" – just the single line. It should then exit (i.e.,) and return False.
If the function processUpdates has successfully processed the country file, then it should proceed to
process the file of updates. It should prompt the user in a similar manner to how the country file was
input, i.e., using a loop to continuously prompt the user until a file was found that existed or until the
user quits.
If the user quits without an update file being selected, then the function processUpdates should write
to the file “output.txt” the message "Update Unsuccessful\n" – just the single line. It should then
exit (i.e.,) and return False.
If an update file is found, then the function processUpdates should process the updates, i.e., update
the information about the countries and then output the new updated list of countries in alphabetical
order to the file “output.txt”. The output should use the method saveCountryCatalogue(self,fname)
from the class CountryCatalogue (see Task 2). It should then exit and return True.
In processing the updates from the update file, the lines may have extra spaces, forgotten semicolons,
etc. Some of these MAY cause exceptions when processing the line – you program should be design
to catch any of these as exception. , e.g. bad values, incorrect format, etc.
The main.py file is provided as the interface to your program. It has been designed to prompt for the
names of a country file and a file of updates and then call the function processUpdates; make sure
that you use these names of functions and methods as described above. You may use the main.py
to test your program in other ways. Two additional data sets of countries have been provided,
data2.txt and data3.txt, as well as two different files of updates, upd2.txt and upd3.txt. You may use
these to test your program. NOTE: while main.py will test some aspects of your program it does not
do a complete and thorough testing – this is left up to you. The TA will use a program similar to,
but different than, main.py to grade your assignment ‐ it will include other tests.
The following may be helpful in sorting data structures
http://pythoncentral.io/how‐to‐sort‐a‐list‐tuple‐or‐object‐with‐sorted‐in‐python/
http://pythoncentral.io/how‐to‐sort‐python‐dictionaries‐by‐key‐or‐value/
Non‐functional Specifications:
1. Include brief comments in your code identifying yourself, describing the program, and describing
key portions of the code.
2. Use Python coding conventions and good programming techniques, for example:
i. Meaningful variable names
ii. Conventions for naming variables and constants
iii. Readability: indentation, white space, consistency
Submit the files in which your classes and functions are defined:
 country.py containing the class Country;
 catalogue.py containing the class CountryCatalogue;
 processUpdates.py contain the function processUpdates.
Make sure you attach your python file to your assignment; DO NOT put the code inline in the textbox.

Homework Answers

Answer #1

Python Code:

File: processUpdates.py

from catalogue import CountryCatalogue
from Country import Country

def processUpdates(cntryFileName,updateFileName):
   """ Processing updates """
   # Opening country file
   fp = open(cntryFileName, "r")
   ofp = open("d:\\Python\\output.txt", "w")
   # Checking status
   if fp == None:
       # Loop till user want to stop processing
       while True:
           # Prompting user
           ch = input("Do you want to Quit? 'Y' (yes) or 'N' (no): ")
          
           # Checking values
           if ch.lower() == "y":
               fName = input("Enter country file name: ")
               # Checking status
               fp = open(cntryFileName, "r")
               if fp != None:
                   break
           elif ch.lower() == "N":
               ofp.write("Update Unsuccessful\n")
               ofp.close()
               return

   # Processing file
   # Creating object
   ccObj = CountryCatalogue(cntryFileName)
  
   # Processing update file
   ufp = open(updateFileName,"r")
   for line in ufp:
       # Stripping new lines
       line = line.strip()
       # Splitting on semicolon
       data = line.split(';')
       # Creating country object
       cObj = Country(data[0], '', '', '')
       # Finding country for existence
       obj = ccObj.findCountry(cObj)
       if obj == None:
           # Fetching values
           for val in data[1:]:
               # Stripping spaces
               val = val.strip()
               # Checking type of update
               if val[0] == 'P':
                   cObj.setPopulation(val[2:])
               elif val[0] == 'A':
                   cObj.setArea(val[2:])
               elif val[0] == 'C':
                   cObj.setContinent(val[2:])
           # Adding to catalogue
           ccObj.addCountry(cObj.getName(), cObj.getPopulation(), cObj.getArea(), cObj.getContinent())
       else:
           # Updating values
           for val in data[1:]:
               # Stripping spaces
               val = val.strip()
               # Checking type of update
               if val[0] == 'P':
                   ccObj.setPopulationOfCountry(cObj, val[2:])
               elif val[0] == 'A':
                   ccObj.setAreaOfCountry(cObj, val[2:])
               elif val[0] == 'C':
                   ccObj.setContinentOfCountry(cObj, val[2:])
          
   # Closing file
   fp.close()
          
   # Printing values
   ccObj.printCountryCatalogue()
  
   # Saving to file
   ccObj.saveCountryCatalogue("d:\\Python\\output.txt")

File: CountryCatalogue.py

from catalogue import CountryCatalogue
from Country import Country
from processUpdates import processUpdates

def main():
   """ Main function """
   # Processing updates
   processUpdates("d:\\Python\\countries.txt", "d:\\Python\\updates.txt")
  
# Calling main
main()  

_____________________________________________________________________________________________________

Screenshot:

_____________________________________________________________________________________________________

Sample Run:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
python problem: ( use a loop to read each character from the string and insert into...
python problem: ( use a loop to read each character from the string and insert into the stack) 1. The function main a5.py continually asks the user for a string, and calls isPalindrome to check whether each string is a palindrome. A palindrome is a word or sequence that reads the same backward as forward, e.g., noon, madam or nurses run. 2. Your function must ignore spaces: when the user enters 'nurses run', the function returns True, to indicate that...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
How do I make this: public class Country {     private String name;     private double area;     private...
How do I make this: public class Country {     private String name;     private double area;     private int population;     public Country(String name, double area, int population) {         this.name = name;         this.area = area;         this.population = population;     }     public double getPopulationDensity() {         return population / area;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public double getArea() {         return area;     }     public void setArea(double area) {         this.area = area;     }     public int getPopulation()...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Challenge: Animal Class Description: Create a class in Python 3 named Animal that has specified attributes...
Challenge: Animal Class Description: Create a class in Python 3 named Animal that has specified attributes and methods. Purpose: The purpose of this challenge is to provide experience creating a class and working with OO concepts in Python 3. Requirements: Write a class in Python 3 named Animal that has the following attributes and methods and is saved in the file Animal.py. Attributes __animal_type is a hidden attribute used to indicate the animal’s type. For example: gecko, walrus, tiger, etc....
So, i have this code in python that i'm running. The input file is named input2.txt...
So, i have this code in python that i'm running. The input file is named input2.txt and looks like 1.8 4.5 1.1 2.1 9.8 7.6 11.32 3.2 0.5 6.5 The output2.txt is what i'm trying to achieve but when the code runs is comes up blank The output doc is created and the code doesn't error out. it should look like this Sample Program Output 70 - 510, [semester] [year] NAME: [put your name here] PROGRAMMING ASSIGN MENT #2 Enter...
In c++ create a class to maintain a GradeBook. The class should allow information on up...
In c++ create a class to maintain a GradeBook. The class should allow information on up to 3 students to be stored. The information for each student should be encapsulated in a Student class and should include the student's last name and up to 5 grades for the student. Note that less than 5 grades may sometimes be stored. Your GradeBook class should at least support operations to add a student record to the end of the book (i.e., the...
I did already posted this question before, I did get the answer but i am not...
I did already posted this question before, I did get the answer but i am not satisfied with the answer i did the code as a solution not the description as my solution, so i am reposting this question again. Please send me the code as my solution not the description In this project, build a simple Unix shell. The shell is the heart of the command-line interface, and thus is central to the Unix/C programming environment. Mastering use of...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...