I'm working on an assignment for my computer class and I'm having a bit of trouble with a question. Question 1 and 2 kind of overlap, so I'll post both, and the code I have so far.
Question 1: Write a function called readCountries that reads a file and returns a list of countries. The countries should be read from this file, which contains an incomplete list of countries with their area and population. Each line in this file represents one country in the following format:
name, area(in km2), population
When opening the file your function should handle any exceptions that may occur. Your function should completely read in the file, and separate the data into a 2-dimensional list. You may need to split and strip the data as appropriate. Numbers should be converted to their correct types. Your function should return this list so that you can use it in the remaining questions.
This is my code for this part:
def readCountries():
countryList = []
for line in open('Countries.py', 'r'):
with open('Countries.py', 'r') as countriesFile:
countries = countriesFile.read()
countryList.append(line.strip().split())
return countryList
Question 2: Write a function called getCountry that takes a string representing a country name as a parameter. First call your answer from question 1 to get the list of countries, then do a binary search through the list and print the country's information if found.
This is my code for this part:
countryList = readCountries()
def getCountry(countryList, name):
lo, hi = 0, len(countryList) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
country = countryList[mid]
test_name = country[0]
if name > test_name:
lo = mid + 1
elif name < test_name:
hi = mid - 1
else:
return country
return countries[lo] if countries[lo][0] == name else None
The output is this: ['Canada', '9976140.0', '35295770'] which is partially what I need, but how would I get it to look like this: Canada, Area: 9976140.0, Population: 35295770?
readCountriesfunction is incorrect. Try displayingcountryList. It retains the commas, and the numbers are strings, which conflicts with your instructions.countryList. Isn't it supposed to retain commas since it's a list?print readCountries(). Note that all data are strings and that all but the last has a comma as its last character.