In: Computer Science
def compareRisk(compareCountry, countryList, filename):
filename = open(filename, "r")
content = filename.readlines()
returnList = []
for row in content [1:]:
line =
row.split(",")
name = line[0]
population =
float(line[1])
infectedPopulation =
float(line[2])
for compareCountry in content:
comparePopulation =
float (line[1])
compareInfected = float
(line[2])
for name in countryList:
if population <
comparePopulation:
if infectedPopulation > compareInfected:
returnList.append(name)
else:
return "No countries"
return returnList
print(compareRisk("Tuvalu", ["Turkmenistan", "Norway",
"Netherlands", "Philippines"], 'covid.csv'))
Why is my code returning an empty list?
This is the covid.cvs snippet for reference:
Country | Cases | Infected |
Aruba | 11883 | 10105 |
Afghanistan | 36651 | 29167 |
Angola | 4858 | 3321 |
Anguilla | 16657 | 11785 |
Ã…land Islands | 59569 | 18462 |
Albania | 87629 | 37130 |
Andorra | 18596 | 1813 |
United Arab Emirates | 22831 | 5957 |
Argentina | 14593 | 11424 |
Armenia | 22058 | 10286 |
American Samoa | 19845 | 16246 |
Antarctica | 72622 | 26437 |
French Southern Territories | 99456 | 12123 |
Antigua and Barbuda | 53272 | 24205 |
Australia | 72149 | 55762 |
Austria | 35311 | 10826 |
Azerbaijan | 9005 | 2600 |
Burundi | 20872 | 20308 |
Belgium | 54222 | 17084 |
check out the solution.
-----------------------------------------------------------
Code:
# function definition
def compareRisk(compareCountry, countryList, filename):
# open file in read mode
filename = open(filename, "r")
# read file contents
content = filename.readlines()
# initialize return list
returnList = []
# save the details of compareCountry
for row in content [1:]:
if compareCountry in row:
line = row.split(",")
comparePopulation = float(line[1])
compareInfected = float(line[2])
# loop through each country in countryList
for name in countryList:
# loop through file
for row in content [1:]:
# if name present in file then only split that row
if name in row:
line = row.split(",")
population = float(line[1])
infectedPopulation = float(line[2])
# after splitting the row
# compare the details with compareCountry details
if population < comparePopulation:
if infectedPopulation > compareInfected:
# if condition met then append to the list
returnList.append(name)
# check if list if empty or not
if(returnList):
return returnList # if not empty , print the list
else:
return "No countries" # if empty, print appropriate message
# function call and print the returned list
print(compareRisk("Andorra", ["Afghanistan", "Armenia", "Angola",
"Anguilla"], 'covid.csv'))
-----------------------------------------------------------------
---------------------------------------------------------------------------------
OUTPUT :
-----------------------------------------------------------
COVID.CSV :
=======================================================