Hurricane Analysis Challenge Project (Python)

Oh thank you @srthomas72 that completely passed under my radar !
And I had a misspell in the second-to-last line on top of that.
Now it’s game on again !

1 Like

Here is my project finished, but not optimized.

I’ll probably rewrite some part as I learn more :

1 Like

Finished my code Completed Hurricane Project Code

I found using Spyder to write the code much more useful than trying to go through Juipyter Notebooks, reason is the variable explorer, early on in the code, had couple of values transposed amongst keys, and being able to drill down into the variables allowed me to see this more clearly than the terminal output or just the int object not iterable or other error message could

My code for this project! Awesome project to learn about dictionaries. Please let me know how I can improve.
thanks!
Codecademy export (github.com)

Has anyone created the initial hurricane dictionary using the zip function? Curious to see that in action

Here’s one version where I used a zip function to make the initial dictionary.

function that makes a dictionary below:

def make_hurricane_dict(names, months, years, winds, areas, damage, deaths):
  dictionary = {}
  zipped = zip(names, months, years, winds, areas, damage, deaths)
  for item in zipped: 
    dictionary.update({ item[0]:  
      { 'Name': item[0],
        'Month': item[1], 
        'Year': item[2],
        'Max Sustained Wind': item[3],
        'Areas Affected': item[4],
        'Damage': item[5],
        'Deaths': item[6]
      } }) 
  return dictionary 
1 Like

Here is my Hurricane Analysis Project

Codecademy Dictionary Hurricane Analysis Project (github.com)

wow this is awesome, thanks!

I know that it doesn’t follow the instructions (to make a function that creates the initial hurricanes dictionary),
but I think using a dict comprehension is the coolest way to create the initial hurricanes dictionary.

hurricanes_dict = { names[i]: 
  { 'Name': names[i],
    'Month': months[i], 
    'Year': years[i],
    'Max Sustained Wind': max_sustained_winds[i],
    'Areas Affected': areas_affected[i],
    'Damage': damages[i],
    'Deaths': deaths[i]
  } for i in range(34) }
1 Like

Here is my attempt!

https://github.com/Dr-Kaboum/Hurricanes-Analysis-.git

My code

here what I had do:

def count_damaged_areas(areas_affected):

areas_name = {}

for area in areas_affected:

for name in area:

  #print(name)

  if name not in areas_name:

    new_key = {name : name.count(name)}

    areas_name.update(new_key)

  elif name in areas_name.keys():

    areas_name[name] += 1

return areas_name

Here’s my current version of this project
from: https://www.codecademy.com/practice/projects/hurricane-analysis

Some of the tasks seemed repetitive, so I made some utility functions that I could reuse on dictionaries or lists. I also tried to clean the location data a little with a function.

# names of hurricanes names = ['Cuba I', 'San Felipe II Okeechobee', 'Bahamas', 'Cuba II', 'CubaBrownsville', 'Tampico', 'Labor Day', 'New England', 'Carol', 'Janet', 'Carla', 'Hattie', 'Beulah', 'Camille', 'Edith', 'Anita', 'David', 'Allen', 'Gilbert', 'Hugo', 'Andrew', 'Mitch', 'Isabel', 'Ivan', 'Emily', 'Katrina', 'Rita', 'Wilma', 'Dean', 'Felix', 'Matthew', 'Irma', 'Maria', 'Michael'] # months of hurricanes months = ['October', 'September', 'September', 'November', 'August', 'September', 'September', 'September', 'September', 'September', 'September', 'October', 'September', 'August', 'September', 'September', 'August', 'August', 'September', 'September', 'August', 'October', 'September', 'September', 'July', 'August', 'September', 'October', 'August', 'September', 'October', 'September', 'September', 'October'] # years of hurricanes years = [1924, 1928, 1932, 1932, 1933, 1933, 1935, 1938, 1953, 1955, 1961, 1961, 1967, 1969, 1971, 1977, 1979, 1980, 1988, 1989, 1992, 1998, 2003, 2004, 2005, 2005, 2005, 2005, 2007, 2007, 2016, 2017, 2017, 2018] # maximum sustained winds (mph) of hurricanes max_sustained_winds = [165, 160, 160, 175, 160, 160, 185, 160, 160, 175, 175, 160, 160, 175, 160, 175, 175, 190, 185, 160, 175, 180, 165, 165, 160, 175, 180, 185, 175, 175, 165, 180, 175, 160] # areas affected by each hurricane areas_affected = [['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], ['The Bahamas', 'Northeastern United States'], ['Lesser Antilles', 'Jamaica', 'Cayman Islands', 'Cuba', 'The Bahamas', 'Bermuda'], ['The Bahamas', 'Cuba', 'Florida', 'Texas', 'Tamaulipas'], ['Jamaica', 'Yucatn Peninsula'], ['The Bahamas', 'Florida', 'Georgia', 'The Carolinas', 'Virginia'], ['Southeastern United States', 'Northeastern United States', 'Southwestern Quebec'], ['Bermuda', 'New England', 'Atlantic Canada'], ['Lesser Antilles', 'Central America'], ['Texas', 'Louisiana', 'Midwestern United States'], ['Central America'], ['The Caribbean', 'Mexico', 'Texas'], ['Cuba', 'United States Gulf Coast'], ['The Caribbean', 'Central America', 'Mexico', 'United States Gulf Coast'], ['Mexico'], ['The Caribbean', 'United States East coast'], ['The Caribbean', 'Yucatn Peninsula', 'Mexico', 'South Texas'], ['Jamaica', 'Venezuela', 'Central America', 'Hispaniola', 'Mexico'], ['The Caribbean', 'United States East Coast'], ['The Bahamas', 'Florida', 'United States Gulf Coast'], ['Central America', 'Yucatn Peninsula', 'South Florida'], ['Greater Antilles', 'Bahamas', 'Eastern United States', 'Ontario'], ['The Caribbean', 'Venezuela', 'United States Gulf Coast'], ['Windward Islands', 'Jamaica', 'Mexico', 'Texas'], ['Bahamas', 'United States Gulf Coast'], ['Cuba', 'United States Gulf Coast'], ['Greater Antilles', 'Central America', 'Florida'], ['The Caribbean', 'Central America'], ['Nicaragua', 'Honduras'], ['Antilles', 'Venezuela', 'Colombia', 'United States East Coast', 'Atlantic Canada'], ['Cape Verde', 'The Caribbean', 'British Virgin Islands', 'U.S. Virgin Islands', 'Cuba', 'Florida'], ['Lesser Antilles', 'Virgin Islands', 'Puerto Rico', 'Dominican Republic', 'Turks and Caicos Islands'], ['Central America', 'United States Gulf Coast (especially Florida Panhandle)']] # damages (USD($)) of hurricanes damages = ['Damages not recorded', '100M', 'Damages not recorded', '40M', '27.9M', '5M', 'Damages not recorded', '306M', '2M', '65.8M', '326M', '60.3M', '208M', '1.42B', '25.4M', 'Damages not recorded', '1.54B', '1.24B', '7.1B', '10B', '26.5B', '6.2B', '5.37B', '23.3B', '1.01B', '125B', '12B', '29.4B', '1.76B', '720M', '15.1B', '64.8B', '91.6B', '25.1B'] # deaths for each hurricane deaths = [90,4000,16,3103,179,184,408,682,5,1023,43,319,688,259,37,11,2068,269,318,107,65,19325,51,124,17,1836,125,87,45,133,603,138,3057,74] # 2 # Update Recorded Damages conversion = {"K": 1000, "M": 1000000, "B": 1000000000, "T": 1000000000000 } #clean the names: def clean(place_list): for i in range(len(place_list)): place_list[i] = place_list[i].title().strip() if place_list[i] == 'The Bahamas': place_list[i] = 'Bahamas' if 'Yucatn' in place_list[i]: place_list[i] = place_list[i].replace('Yucatn', 'Yucatan') if '(' in place_list[i]: open = place_list[i].index('(') close = place_list[i].index(')') inside = place_list[i][open+1 :close] place_list[i] = place_list[i][:open] if inside.lower().startswith('especially'): inside = inside[11:] place_list.append(inside) if 'The Carolinas' in place_list: place_list.remove('The Carolinas') place_list.extend(['North Carolina', 'South Carolina']) if 'Virgin Islands' in place_list: place_list.remove('Virgin Islands') place_list.extend(['U.S. Virgin Islands', 'British Virgin Islands']) if 'Antilles' in place_list: place_list.remove('Antilles') place_list.extend(['Greater Antilles', 'Lesser Antilles']) #return place_list for i in range(len(areas_affected)): clean(areas_affected[i]) def to_int(stuff): if isinstance(stuff, str): if stuff.isdigit(): return int(stuff) if stuff[-1] in conversion and stuff[0].isdigit(): if '.' in stuff: part = stuff[:-1].split('.') start = int(part[0]) * conversion[stuff[-1]] d = len(part[1]) end = int(part[1]) * conversion[stuff[-1]] // 10**d return start + end else: return int(stuff[:-1]) * conversion[stuff[-1]] else: return 0 elif isinstance(stuff, list): return [to_int(item) for item in stuff] def to_float(stuff): if isinstance(stuff, str): if stuff[-1] in conversion and stuff[0].isdigit(): return float(stuff[:-1]) * conversion[stuff[-1]] elif stuff.isdigit(): return float(stuff) else: #'Damages not recorded' return stuff elif isinstance(stuff, list): return [to_float(item) for item in stuff] # test function by updating damages damages = to_float(damages) #print(damages) # 3 # Create a Table table = list(zip(names, months, years, max_sustained_winds, areas_affected, damages, deaths)) column_names = ['Name', 'Month', 'Year', 'Max Sustained Wind', 'Areas Affected', 'Damage', 'Deaths'] #print(table[0]) def make_hurricane_dict(names, months, years, winds, areas, damage, deaths): dictionary = {} zipped = zip(names, months, years, winds, areas, damage, deaths) for item in zipped: dictionary.update({ item[0]: { 'Name': item[0], 'Month': item[1], 'Year': item[2], 'Max Sustained Wind': item[3], 'Areas Affected': item[4], 'Damage': item[5], 'Deaths': item[6] } }) return dictionary # Create and view the hurricanes dictionary #hurricanes_by_name = make_dict() hurricanes_dict = make_hurricane_dict(names, months, years, max_sustained_winds, areas_affected, damages, deaths) #print(hurricanes_dict['Cuba I']) #print(hurricanes_dict['Ivan']) # 4 # Organizing by Year def group(stuff, by=None, index_as_key=True, apply=None): """apply is a function to use on each item, whose output will be used to group the items""" if apply is None or apply is False: key_for = lambda x: x elif isinstance(apply, dict): key_for = apply.get elif isinstance(apply, (list, tuple)): key_for = apply.index else: key_for = apply grouped = {} if isinstance(stuff, dict): indecies = stuff.keys() elif isinstance(stuff, (list, tuple)): indecies = range(len(stuff)) if by is None: for i in indecies: #current = stuff[i] if apply is None: current = stuff[i] else: current = key_for(stuff[i]) if current not in grouped: grouped[current] = [] grouped[current].append(i) #list of indecies else: for i in indecies: #current = stuff[i][by] if apply is None: current = stuff[i][by] else: current = key_for(stuff[i][by]) if index_as_key: to_add = i else: to_add = stuff[i] if current not in grouped: grouped[current] = [] grouped[current].append(to_add) #list of indecies return grouped def make_dict_by_year(data): return group(data, by='Year', index_as_key=False, apply=None) # create a new dictionary of hurricanes with year and key hurricanes_by_year = make_dict_by_year(hurricanes_dict) #print(hurricanes_by_year[1932], '\n') #print(hurricanes_by_year[2007], '\n') # 5 # Counting Damaged Areas def get_freq_of_list_items_in_col(stuff, column=None): frequencies = {} if isinstance(stuff, dict): indecies = stuff.keys() elif isinstance(stuff, (list, tuple)): indecies = range(len(stuff)) if column is None: for i in indecies: for this_one in stuff[i]: if this_one not in frequencies: frequencies[this_one] = 1 else: frequencies[this_one] += 1 else: for i in indecies: for this_one in stuff[i][column]: if this_one not in frequencies: frequencies[this_one] = 1 else: frequencies[this_one] += 1 return frequencies # create dictionary of areas to store the number of hurricanes that affected that area hurricane_count_by_area = get_freq_of_list_items_in_col(hurricanes_dict, 'Areas Affected') #for area, freq in hurricane_count_by_area.items(): #print(area, freq) # 6 # Calculating Maximum Hurricane Count # function to get maximum [and its index] # (only for ints and floats, otherwise gives 0) def max_of(stuff, include_index=False, column=None): if isinstance(stuff, dict): indecies = list(stuff.keys()) elif isinstance(stuff, (list, tuple)): indecies = range(len(stuff)) else: indecies = range(len(stuff)) if column is None: index_of_max = indecies[0] maximum = stuff[indecies[0]] if not isinstance(maximum, (int, float)): maximum = 0 for i in indecies: if not isinstance(stuff[i], (int, float)): continue if stuff[i] > maximum: maximum = stuff[i] index_of_max = i else: index_of_max = indecies[0] maximum = stuff[indecies[0]][column] if not isinstance(maximum, (int, float)): maximum = 0 for i in indecies: if not isinstance(stuff[i][column], (int, float)): continue if stuff[i][column] > maximum: maximum = stuff[i][column] index_of_max = i if include_index: return (index_of_max, maximum) else: return maximum def get_most_frequent_area(hurricane_dict): freqs = get_freq_of_list_items_in_col(hurricanes_dict, 'Areas Affected') return max_of(freqs, include_index=True) # find most frequently affected area and the number of hurricanes involved most_affected, most_hurricanes = get_most_frequent_area(hurricanes_dict) print("The greatest number of cat5 hurricanes was at location: {}, \nnumber of hurricanes: {}".format(most_affected, most_hurricanes)) print() # 7 # Calculating the Deadliest Hurricane # find highest mortality hurricane and the number of deaths def get_deadliest_storm(hurricane_dict): return max_of(hurricane_dict, include_index=True, column="Deaths") deadliest_hurricane, max_deaths = get_deadliest_storm(hurricanes_dict) print("deadliest hurricane:", deadliest_hurricane) print("deaths:", max_deaths) print() # 8 # Rating Hurricanes by Mortality mortality_scale = {0: 0, 1: 100, 2: 500, 3: 1000, 4: 10000} #mortality_scale = [0, 100, 500, 1000, 10000] def classify_into_bracket(value, brackets): if (not isinstance(value, (int, float))) and isinstance(list(brackets.values())[0], (int, float)): return None if isinstance(brackets, dict): pairs = sorted(list(brackets.items())) elif isinstance(brackets, (list, tuple)): pairs = list(zip(range(len(brackets)), brackets)) #pairs = list(enumerate(brackets)) for (category, upper_bound) in pairs: if value <= upper_bound: return category if isinstance(pairs[-1][0], int): return pairs[-1][0] + 1 def classify_all(data, brackets, by=None): if isinstance(data, (list, tuple)): if by is None: return [classify_into_bracket(value, brackets) for value in data] else: return [classify_into_bracket(row[by], brackets) for row in data] elif isinstance(data, dict): if by is None: return {key: classify_into_bracket(data[key], brackets) for key in data} else: return {key: classify_into_bracket(data[key][by], brackets) for key in data} hurricane_severity_by_deaths = classify_all(hurricanes_dict, mortality_scale, by='Deaths') def get_hurricane_by_severity_from_mortality(storm_data): classify = lambda x: classify_into_bracket(x, mortality_scale) return group(storm_data, by='Deaths', index_as_key=False, apply=classify) hurricanes_by_severity = get_hurricane_by_severity_from_mortality(hurricanes_dict) # categorize hurricanes in new dictionary with mortality severity as key classify = lambda x: classify_into_bracket(x, mortality_scale) hurricanes_by_severity = group(hurricanes_dict, by='Deaths', index_as_key=False, apply=classify) # 9 # Calculating Hurricane Maximum Damage # find highest damage inducing hurricane and its total cost costliest_hurricane, max_cost = max_of(hurricanes_dict, column='Damage', include_index=True) print("costliest hurricane:", costliest_hurricane) print("damage: $", max_cost) print() # 10 # Rating Hurricanes by Damage damage_scale = { 0: 0, 1: 100000000, 2: 1000000000, 3: 10000000000, 4: 50000000000 } hurricane_severity_by_damage = classify_all(hurricanes_dict, damage_scale, by='Damage') def get_hurricane_by_severity_from_damage(storm_data): classify = lambda x: classify_into_bracket(x, damage_scale) if isinstance(x, (int, float)) else 0 return group(storm_data, by='Damage', index_as_key=False, apply=classify) # categorize hurricanes in new dictionary with damage severity as key hurricanes_by_severity = get_hurricane_by_severity_from_damage(hurricanes_dict) # categorize hurricanes in new dictionary with damage severity as key classify = lambda x: classify_into_bracket(x, damage_scale) hurricane_by_severity = group(hurricanes_dict, by='Damage', index_as_key=False, apply=classify) print("Hurricanes by severity according to damage scale:") for category in hurricanes_by_severity: print(category, end=": [") print(", ".join([storm['Name'] for storm in hurricanes_by_severity[category]]) +"]")

If anyone has any comments or suggestions, I’d be interested in reading them.

Here’s my code. Again tried to make some of the functions more generic so they could be reused or changed depending on the variables passed in.

Hi everyone,
I have completed this project and this is my solution.

Here’s my solution. I need to learn how to make it a lot easier to understand/read.

Here is my code.

As everyone has mentioned there were a lot of repetitive tasks to be completed. You can design a single function that could complete a few of the problems.

However, I decided to go through each problem with a bit more elbow grease in order to practice going through the logic of how to solve each problem.

I’ve also tried to add detailed notes to each problems logic as I thought through how to solve it.

Happy to receive any feedback!