Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.92 KB | None | 0 0
  1. ###Assignment 4
  2. ###The program will set and get country along with information such as population, are and population density. Also you can modify, save and edit country list along with thier information
  3.  
  4. #the following class is named Country and it will set and get country informatioon
  5.  
  6. class Country: #creating a country class
  7. ###### creating the construct method
  8. def __init__(self,name,pop,area,continent): #creating construct and accpting name, population, area and content prameter
  9. self._name = name # setting construct to class variables. This description applies for line 10 to 13
  10. self._pop = pop #setting self._pop
  11. self._area = area #setting up self._area
  12. self._continent = continent #setting up self._continet variable
  13. self._popDensity = round((self._pop/self._area), 2) #calculating population density which is equal to population /area
  14. ####creating repr method
  15. def __repr__(self): #setting up repesentation method
  16. return self._name + " is in " + self._continent + " with a population density of " + str(self._popDensity) + "pop is " +str(self._pop) + " area " + str(self._area) #will produce a genrilzed description of the instant
  17. #China is in Asia with a population density of 4.56
  18.  
  19. ###creating setting method named set populatin which it will set up population
  20. def setPopulation(self,pop): #define population
  21. self._pop = pop #setting self.pop to equal pop which is provided upon calling
  22.  
  23. ###setting population density method
  24. def setPopDensity(self): #define setPop Density method
  25. self._popDensity = self._pop/self._area #setting self._popDensity by applying the equation of population/area
  26.  
  27. ####setting the getter method for name
  28. def getName(self): #creating the getName method
  29. return self._name #returing the name that was set in the construct
  30.  
  31. ####definging getting area method which geting contry's area
  32. def getArea(self):
  33. return self._area #it return the area of the country
  34.  
  35. ####defing get population which return the population of the conuntry
  36. def getPopulation(self): #definging the function
  37. return self._pop #returing the population
  38.  
  39. ###definging the get continent which return the continent of a selected country
  40. def getContinent(self): #define the function
  41. return self._continent #returns the inforatmoin to the user
  42.  
  43. ###defingin the get population density which returns the density of a country
  44. def getPopDensity(self): #definging the function
  45. return self._popDensity #it return the population density to the user
  46.  
  47.  
  48. ########Creating a class called CountryCatalogue which reads a file, import the content of a file and modify the information and then save them to a file
  49. class CountryCatalogue: #creating a class
  50. ###creating a construct that takes in a file name
  51. def __init__(self, file):
  52. try: #it tries the following line incase the name of the file was faults
  53. self._file = open(file, "r") #open the file
  54. self._catalogue = {} #creating a dictionary type list
  55. self._cDictionary = {} #same as upove
  56.  
  57. self._cFile = open("continent.txt", "r") #opening continenet.txt file
  58. self._cFile.readline() #reading and ignoring the first line
  59. for line in self._cFile: #read everyline after the first line and then perform the following actiosn
  60. line = line.split(",") #spliting and convering text into lists
  61. self._cDictionary[line[0]]=line[1].replace("\n","")
  62.  
  63. #print(self._cDictionary)
  64.  
  65. self._file.readline() #read the first line
  66. for line in self._file: #for everyline in the self._file do the follwing
  67. line = line.replace(",","").split("|") #replace and split the line into lists
  68. lineC = Country(line[0],int(line[1]),float(line[2]),self._cDictionary[line[0]]) #creating an object using the Country class
  69. self._catalogue[line[0]]=lineC
  70. self._cFile.close() #close self._cFile
  71. self._file.close() #close self._file
  72. #print(self._catalogue)
  73.  
  74. except IOError : #creat an exception incase the user input the wrong file name
  75. print("Error: file was not found.")
  76. sys.exit() #it exit the program
  77.  
  78. except ValueError :#create an aexcpetion incase the user ad unreadable file
  79. print("Error: invalid file.")
  80. sys.exit() #it exits the program
  81.  
  82. except RuntimeError as error :
  83. print("Error:", str(error))
  84. sys.exit() #it exits the program
  85. #print(self._catalogue)
  86.  
  87. ###defing a add country method that takes in country name, population, area and continent
  88. def addCountry(self, name, pop, area, continent): #defining the function
  89. if name.title() in self._cDictionary: #check if name exist in the cDictionary
  90. print("Country does not exist, Please renter the information") #it alerts that country already exist
  91. name = str(input("Please input country's name: ")).title() #it asks for country name
  92. pop = int(input("Please input {} population: ".format(name))) #it asks for population
  93. area = float(input("Please input {} area: ".format(name))) #it asks for area of the country
  94. continent = str(input("Please input {} continent: ".format(name))).title() #it asks for the continent name
  95. self.addCountry(name.title(), pop, area, continent.title()) #it calls it self to check and add the country
  96. else:#if name does not exist
  97. self._catalogue[name] = Country(name.title(), int(pop), float(area), continent.title()) #it creates an object
  98. self._cDictionary[name] = continent #it adds the name and continent to cDictionary
  99. print("{} has successfully been added to the list".format(name)) #it alerts that the name was sucessfull
  100. #print(self._cDictionary)
  101. #print(self._catalogue)
  102.  
  103. ### define a method that delet a country information from cDictionary and catalogue lists
  104. def deletCountry(self, name): #defien a function
  105. if name in self._cDictionary: #for every item in cDictionary
  106. self._cDictionary.pop(name) #remove the name from cDictionary
  107. self._catalogue.pop(name) #remove the name from catalogue
  108. print("country has been remvoed") #it alerts upon completion
  109.  
  110. else:
  111. print("name does not exist") #it alerts if country does not exist
  112.  
  113.  
  114. ###define a mothod that finds a countyr information
  115. def findCountry(self, name): #define a function
  116. if name in self._cDictionary: #for every itme on the list
  117. print(name, " Summary: ",self._catalogue[name]) #it prints summary of countyr name
  118. print(name, " Area: ",self._catalogue[name].getArea()) #it prints out the area
  119. print(name, " Population: ", self._catalogue[name].getPopulation()) #it prints out the population
  120. else: #otherwise
  121. print("Country does not exist") #it alerts that the county does exist
  122.  
  123.  
  124. ### define a method that filter countries by contient inputed by user
  125. def filterCountriesByContinent(self, name): #define a function
  126. countries = set() #define a set
  127. for cat in self._catalogue: #for every item in catalogue
  128. if self._catalogue[cat].getContinent() == name: #if name matches to alist itme
  129. countries.add(cat) #it adds the country
  130.  
  131. print("the following countries belong to the continent of ", name, " are ", countries) #it prints out the contires list
  132.  
  133.  
  134. ### define and print country's catalouge to the user
  135. def printCountryCatalogue(self):
  136. for cat in self._catalogue:
  137. print(self._catalogue[cat])
  138.  
  139. ### define a function that sets the popualtion of a selected country
  140. def setPopulationOfASelectedCountry(self,name, pop): #defining the method that takes two variables
  141. if name.title() in self._catalogue: #if name exist in the list
  142. self._catalogue[name].setPopulation(pop) #set the population number
  143. self._catalogue[name].setPopDensity() #set the population density
  144. print(name, " population has been modified to ", self._catalogue[name].getPopulation()) #print the population
  145. print(name, " population density is ", self._catalogue[name].getPopDensity()) #print the population density
  146. #print(self._catalogue[name]) #print self._catalogue[name]
  147. else:
  148. print("You can not change the population because {} does not exist in the database".format(name))
  149.  
  150. ### find country with the largest population
  151. def findCountryWithLargestPop(self): #defien the function
  152. initPop = 0 #define initial population
  153. countryName = "" #define country name
  154. for cat in self._catalogue: #for each item in self._catalogue
  155. if self._catalogue[cat].getPopulation() > initPop: #if country populatrion is bigger than init
  156. initPop = self._catalogue[cat].getPopulation() #set initPop to equal to new population
  157. countryName = self._catalogue[cat].getName() #set country to equal the contry with the larger population
  158. print("The country with the largest population is ", countryName,": ", initPop) #print country and population
  159.  
  160. ### define a method that find the smallest area
  161. def findCountryWithSmallestArea(self): #define the function
  162. lowestTrue = True #set lowstTrue to True
  163. country = "" #set country to equal nothing
  164. lowestArea = 0 #set lowerstArea to equal 0
  165. for cat in self._catalogue: #for each item on the list
  166. if lowestTrue: #if true
  167. lowestArea = self._catalogue[cat].getArea() #set lowestARea to the lowestArea
  168. lowestTrue = False #change lowestTrue to false
  169. if self._catalogue[cat].getArea() < lowestArea: #if the current is lowest area is lower than the curnet lowestArea
  170. lowestArea = self._catalogue[cat].getArea() #set lowestArea to the new area
  171. country = self._catalogue[cat].getName() #set country to the current country with the lowest area
  172. print(country, " has the smallest area of ", lowestArea) #print the country and area
  173.  
  174. ### the following method
  175. def filterCountriesByPopDensity(self, min, max):
  176. countries = set() #it create a set
  177. for cat in self._catalogue: #for every item in the list
  178. if self._catalogue[cat].getPopDensity()>=min and self._catalogue[cat].getPopDensity()<=max:
  179. countries.add(self._catalogue[cat].getName()) #it adds to the list
  180. print("The following countries population density falls between {} and {}".format(min,max), " are " ,str(countries).replace("{", "").replace("'","").replace("}","")) #it prints out the list
  181.  
  182. ###define a functionthat find the most populous continent
  183. def findMostPopulousContinent(self): #define the function
  184. northAmerica={} #define a dict for north america
  185. naTotal=0 #define north america to equal 0
  186. southAmerica = {} #define a dict for south america
  187. saTotal=0 #define south america to equal 0
  188. asia={} ##define a dict for aisa
  189. aTotal=0 #define asia to equal 0
  190. africa={} #define a dict for africa
  191. afTotal = 0 #define africa to equal 0
  192. europe = {} #define a dict for europe
  193. eTotal = 0 #define europe to equal 0
  194. australia={} #define a dict for australia
  195. auTotal = 0 #define australia to equal 0
  196. other = {}
  197. oTotal = 0
  198. for cat in self._catalogue: #for every item on the list
  199. if self._catalogue[cat].getContinent() == 'North America': #if item is equal to North America
  200. northAmerica[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population number
  201. naTotal = naTotal + self._catalogue[cat].getPopulation() #incrument the total with the population
  202. elif self._catalogue[cat].getContinent() == 'Asia': #if item is equal to North America
  203. asia[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num
  204. aTotal = aTotal + self._catalogue[cat].getPopulation() #incrument the total with the population
  205. elif self._catalogue[cat].getContinent() == 'South America': #if item is equal to south america
  206. southAmerica[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num
  207. saTotal = saTotal + self._catalogue[cat].getPopulation()#incrument the total with the population
  208. elif self._catalogue[cat].getContinent() == 'Africa': #if item is equal to africa
  209. africa[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num
  210. afTotal = afTotal + self._catalogue[cat].getPopulation() #incrument the total with the population
  211. elif self._catalogue[cat].getContinent() == 'Europe': #if item is equal to europe
  212. europe[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num
  213. eTotal = eTotal + self._catalogue[cat].getPopulation() #incrument the total with the population
  214. elif self._catalogue[cat].getContinent() == 'Australia': #if item is equal to australia
  215. australia[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num
  216. auTotal = auTotal + self._catalogue[cat].getPopulation() #incrument the total with the population
  217. else:
  218. other[cat]=self._catalogue[cat].getPopulation() ##if item is equal to something else
  219. oTotal = oTotal + self._catalogue[cat].getPopulation() #other content
  220. test = {"North America": naTotal, "South America":saTotal, "Asia":aTotal,"Africa":afTotal, "Europe": eTotal}
  221. total = 0
  222. continent = ""
  223. for i in test:
  224. if test[i]> total:
  225. total = test[i]
  226. continent = i
  227. print(continent, "is the most populated continent with total of ", total)
  228. if continent =="North America": #if continent is equal to North America
  229. self.displayList(northAmerica) #calculate the information using displayList
  230. elif continent =='South America': #if continent is equal to South America
  231. self.displayList(southAmerica) #calculate the information using displayList
  232. elif continent.title() =='Europe': #if continent is equal to Europe
  233. self.displayList(europe) #calculate the information using displayList
  234. elif continent.title()=='Asia': #if continent is equal to Asia
  235. self.displayList(asia) #calculate the information using displayList
  236. elif continent.title() =='Africa': #if continent is equal to Africa
  237. self.displayList(africa) #calculate the information using displayList
  238. elif continent.title() =='Australia': #if continent is equal to Australia
  239. self.displayList(australia) #calculate the information using displayList
  240. else:
  241. self.displayList(other) #if continent is equal to other
  242.  
  243.  
  244. ##defining a method that saves the information to a file
  245. def saveCountryCatalogue(self, fileName): #define a function
  246. file = open(fileName,'w') #it opens fileName and then write
  247. writeFile = False #set writeFile to false
  248. for i in sorted(self._catalogue): #for every item that is sorted in a list
  249. output = self._catalogue[i].getName()+" | "+ self._catalogue[i].getContinent()+" | "+ str(self._catalogue[i].getPopulation())+" | "+ str(self._catalogue[i].getPopDensity()) +"\n" #it genrate a string
  250. file.write(output) #it writes to a file
  251. print("the file was saved") #it alert the file was saved
  252. file.close() #it closes the file
  253.  
  254. ###The following function will return the list in a point form style
  255. def displayList(self, list): #define the method that takes a list as an argument
  256. for i in list: #for each item on the list
  257. print(i,": ", list[i],end=" \n") #print the itme and end with a new line
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement