IN PYTHON This function will take as input a list and a string. The list will be
ID: 3677228 • Letter: I
Question
IN PYTHON
This function will take as input a list and a string. The list will be a list of lists – each element will consist of a list containing a first element which is a list with two strings – the first string indicating a city and the second indicating a state – and a second element which is an integer indicating the population for that state: [[[city,state],population], [[city,state],population] …] The second parameter is a string giving a state abbreviation. The function will return a string with the city name, state and population for the city that has the largest population in the state given as a parameter to the function. If a state is given that is not in the list, a string with the error message as shown will be returned: "State not found." If the clist is an empty list, a string with the error message as shown will be returned: "List is empty."
Output MUST BE as presented in the EXACT format used in the call to the check function at the bottom of the template:
SAMPLE RUNS:
cityPop([[["Indianapolis","IN"],820445],[["Joliet","IL"],147433],[["Fort Wayne", "IN"],253691],[["Cedar Rapids","IO"],12429],[["Chicago","IL"],2695598],[["Evansville","IN"],117429],[["South Bend","IN"],1011681],[["Des Moines","IO"],207510],[["Davenport","IO"],102157],[["Sioux City","IO"],82459],[["Rockford","IL"],152871],[["Aurora","IL"],197899]],"IN") will return in this EXACT format: ('South Bend', 'IN', 1011681)
Explanation / Answer
def cityPop(list,string):
tot=len(list) #total length of the input list
if(tot==0): #If input list is empty, return "List is empty."
return "List is empty."
ans=[] #empty list to store the ans
for i in range(tot): #Iterate through all the elements of the input list
if(list[i][0][1]==string): #if input string matches with the current state
if(len(ans)==0): #First list element with given state, store it as ans
ans.append(list[i])
else:
if(ans[0][1]<list[i][1]): #if population of this element is greater than previously stored element, update the ans
ans.pop();
ans.append(list[i])
if(len(ans)==0): #If the input is state not found in the given list, returning "State not found."
return "State not found."
else:
return ans