I’m just curious what people think of this code I wrote to rate hurricanes according to a mortality rate scale. What could I have done better? I checked the given solution, and it seems like I may have over complicated the solution.
This is my solution:
The idea was to iterate through each of the scale ratings and then append the correct hurricanes to that rating.
def mortality_rating(my_dict):
mortality_scale = {
0: 0,
1: 100,
2: 500,
3: 1000,
4: 10000
}
mort_list = []
mortality_ratings = {}
for scale in mortality_scale.items():
for cane in my_dict:
if scale[0] != 4:
if my_dict[cane]['Deaths'] >= scale[1] and my_dict[cane]['Deaths'] < mortality_scale[scale[0] + 1]:
mort_list.append(cane)
elif my_dict[cane]['Deaths'] >= scale[1]:
mort_list.append(cane)
mortality_ratings.update({scale[0]:mort_list})
mort_list = []
return mortality_ratings
Here’s the given solution:
def categorize_by_mortality(hurricanes):
"""Categorize hurricanes by mortality and return a dictionary."""
mortality_scale = {0: 0,
1: 100,
2: 500,
3: 1000,
4: 10000}
hurricanes_by_mortality = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
for cane in hurricanes:
num_deaths = hurricanes[cane]['Deaths']
if num_deaths == mortality_scale[0]:
hurricanes_by_mortality[0].append(hurricanes[cane])
elif num_deaths > mortality_scale[0] and num_deaths <= mortality_scale[1]:
hurricanes_by_mortality[1].append(hurricanes[cane])
elif num_deaths > mortality_scale[1] and num_deaths <= mortality_scale[2]:
hurricanes_by_mortality[2].append(hurricanes[cane])
elif num_deaths > mortality_scale[2] and num_deaths <= mortality_scale[3]:
hurricanes_by_mortality[3].append(hurricanes[cane])
elif num_deaths > mortality_scale[3] and num_deaths <= mortality_scale[4]:
hurricanes_by_mortality[4].append(hurricanes[cane])
elif num_deaths > mortality_scale[4]:
hurricanes_by_mortality[5].append(hurricanes[cane])
return hurricanes_by_mortality
I’m not sure which is the better code because neither are necessarily scalable. I think my solution could be changed at the if scale[0] != 4:
part to be whatever is at the end of the key list, but I’m not exactly sure of the best way to do that either.