Hurricane Analysis Challenge Project (Python)

My solution to the Hurricane Analysis project. New to python and coding. Would appreciate any suggestions.

Hi, thanks for the project! Here is my version GitHub - halb-nat/hurricanes

Here’s my code. It took me half day to solve all. Appreciate and thanks for any review. :grinning:

Hello everyone. This is my code for the Hurricane Analysis project using Python. I don’t know if it’s just me, but the jump from what’s taught in the lessons to what we actually need to code was a challenge for me. However, I am thankful for the practice and i hope to get better at more intuitively knowing what to do vs. searching for help. :sweat_smile:

https://gist.github.com/cheycodes23/5b36c2a0ae86bab20742f4abbbebe708

# 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]

# 1
# Update Recorded Damages
def update_damages(damages):
    new_damages = []
    conversion = {"M": 1000000,
                  "B": 1000000000}
    for cost in damages:
        if cost == 'Damages not recorded':
            new_damages.append(cost)
        elif cost[-1] in conversion.keys():
            new_cost = float(cost[:-1]) * conversion[cost[-1]]
            new_damages.append(new_cost)
    return new_damages

# test function by updating damages

updated_damages = update_damages(damages)
print(updated_damages)

# 2 
# Create a Table
def generate_dictionary(names,
                        months,
                        years,
                        max_sustained_winds,
                        areas_affected,
                        updated_damages,
                        deaths):
    dictionary = {}
    for index in range(len(names)):
        dictionary[names[index]] = {
            "Name": names[index],
            "Month": months[index],
            "Year": years[index],
            "Max Sustained Wind": max_sustained_winds[index],
            "Areas Affected": areas_affected[index],
            "Damages": updated_damages[index],
            "Deaths": deaths[index]
        }
    return dictionary

# Create and view the hurricanes dictionary
hurricanes = generate_dictionary(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths)
print(hurricanes)


# 3
# Organizing by Year

# create a new dictionary of hurricanes with year and key
def set_dictionary_keys_by_year(hurricanes):
    current_cane_dict = {}
    for key, value in hurricanes.items():
        current_year = hurricanes[key]["Year"]
        if not current_cane_dict.get(current_year):
            current_cane_dict[current_year] = [value]
        else:
            current_cane_dict[current_year].append(value)
    return current_cane_dict


current_cane_dict = set_dictionary_keys_by_year(hurricanes)
print("---------------Current Cane----------------")
print(current_cane_dict)
# 4
# Counting Damaged Areas

# create dictionary of areas to store the number of hurricanes involved in
#dict is count_affected_dict
#key is areas_affected
#value is count_affected
def count_affected_areas(hurricanes):
  count_affected_dict = {}
  for value in hurricanes.values():
    for i in value["Areas Affected"]:
      if i not in count_affected_dict:
        count_affected_dict[i] = 1
      else:
        count_affected_dict[i] += 1
  return count_affected_dict
    
count_affected_dict = count_affected_areas(hurricanes)
print("----------These are the hurricane counts----------")
print(count_affected_areas(hurricanes))
  



# 5 
# Calculating Maximum Hurricane Count
def most_affected_areas(count_affected_dict):
  most_affected = {}
  count = 0
  for k, v in count_affected_dict.items():
    if v > count:
      most_affected[k] = v
      count = v
  return most_affected
  

most_affected = most_affected_areas(count_affected_dict)

# find most frequently affected area and the number of hurricanes involved in
print("-----This is the most affected area and it\'s number of occurances : " + str(most_affected.items()))

# 6
# Calculating the Deadliest Hurricane
def greatest_death(hurricanes):
  max_death = ""
  count = 0
  for i in hurricanes:
    if hurricanes[i]["Deaths"] > count:
      max_death = i
      count = hurricanes[i]["Deaths"]
  return max_death, count

max_death, count = greatest_death(hurricanes)


# find highest mortality hurricane and the number of deaths
print("This is the deadliest hurricane and the number of deaths: " + str(greatest_death(hurricanes)))
# 7
# Rating Hurricanes by Mortality

mortality_scale = {0: 0,
                   1: 100,
                   2: 500,
                   3: 1000,
                   4: 10000}

# categorize hurricanes in new dictionary with mortality severity as key

def rate_by_mortality(hurricanes):
  hurricane_mortality = {0: [], 1: [], 2: [], 3: [], 4: [], 5: []}
  for name in hurricanes:
    if hurricanes[name]['Deaths'] == mortality_scale[0]:
      hurricane_mortality[0] = name
    elif mortality_scale[0] < hurricanes[name]['Deaths'] <= mortality_scale[1]:
      hurricane_mortality[1].append(name)
    elif mortality_scale[1] < hurricanes[name]['Deaths'] <= mortality_scale[2]:
      hurricane_mortality[2].append(name)
    elif mortality_scale[2] < hurricanes[name]['Deaths'] <= mortality_scale[3]:
      hurricane_mortality[3].append(name)
    elif mortality_scale[3] < hurricanes[name]['Deaths'] <= mortality_scale[4]:
      hurricane_mortality[4].append(name)
    else:
            hurricane_mortality[5].append(name)
  return hurricane_mortality

hurricane_mortality = rate_by_mortality(hurricanes)
print('These are the hurricanes categorized by the Mortality Scale---------------------')
print(hurricane_mortality)  


# 8 Calculating Hurricane Maximum Damage
def highest_damage(hurricanes):
  max_damage = []
  for name in hurricanes:
    if hurricanes[name]['Damages'] != 'Damages not recorded':
      max_damage.append(hurricanes[name]['Damages'])
  greatest_damage = max(max_damage)
  for name in hurricanes:
    if hurricanes[name]['Damages'] == greatest_damage:
      return name, greatest_damage

# find highest damage inducing hurricane and its total cost
print("This is the most expensive hurricane and the cost: " + str(highest_damage(hurricanes)))

# 9
# Rating Hurricanes by Damage

damage_scale = {0: 0,
                1: 100000000,
                2: 1000000000,
                3: 10000000000,
                4: 50000000000}
  
# categorize hurricanes in new dictionary with damage severity as key
def rate_by_damage(hurricanes):
  hurricane_damage = {'No Damage': [], 1: [], 2: [], 3: [], 4: [], 5: []}
  for name in hurricanes:
    if hurricanes[name]['Damages'] == 'Damages not recorded':
      hurricane_damage['No Damage'].append(name)
    elif damage_scale[0] < hurricanes[name]['Damages'] <= damage_scale[1]:
      hurricane_damage[1].append(name)
    elif damage_scale[1] < hurricanes[name]['Damages'] <= damage_scale[2]:
      hurricane_damage[2].append(name)
    elif damage_scale[2] < hurricanes[name]['Damages'] <= damage_scale[3]:
      hurricane_damage[3].append(name)
    elif damage_scale[3] < hurricanes[name]['Damages'] <= damage_scale[4]:
      hurricane_damage[4].append(name)
    else:
      hurricane_damage[5].append(name)
  return hurricane_damage


hurricane_damage = rate_by_damage(hurricanes)
print('These are the hurricanes categorized by the Damage Scale---------------------')
print(hurricane_damage)  
1 Like

My Hurricanes Analysis

Check, helping yourself or leave feedback for me. Thanks and good luck, guys!

Here is my first project…

Here’s my code: P.S. I didn’t create functions but just immediately started loops. Should I polish them with functions?

My code may differ since I didn’t use the given dictionary codes for the mortality and damages scale.

Please comment, make suggestions, ask questions. Thanks!

Here is my Solution at GitHub
GItHub Solution

link doesn’t work for me. is it working for you?

I have made small tweaks to few solutions. For example:

def the_most_at_selected_cathegory(hurricanes_by_name_dict: dict,cathegory: str = 'Death') -> None:
    # find the highest cane in any cathegory
    if cathegory not in list(hurricanes_by_name_dict.values())[0].keys(): raise Exception("Sorry, no cathegory {} available.".format(cathegory)) 
    max_at_selected_cathegory = 0
    for name,cane in hurricanes_by_name_dict.items():
        cane_at_selected_cathegory = cane[cathegory]
        try:
            if cane_at_selected_cathegory > max_at_selected_cathegory: max_at_selected_cathegory = cane_at_selected_cathegory
        except TypeError:
            continue

    print('{} has maximum of {} in {} cathegory'.format(name, max_at_selected_cathegory, cathegory))

Is anybody interested in mutual review of the rest? In that case I would make a pull request.

I look forward to your suggestions :slight_smile:

Matej

Hi everybody! Here my Hurricane Project.

My_Project: Hurrican Analysis

Please, let me know if this code can be improved in anyway.
Thanks

Have a Good Code

Marta

Hello, this is my solution with some help from the solution: Solution

Here it’s my solution. it was a funny challenge. Hopefully I will receive some feedback.

I just made my first upload to github, hopefully I’ll learn how to properly use it in the future

Here is my code. Decided to have some fun with this project and try some new modules and techniques.
https://gist.github.com/codecademydev/69b25e1e9312d2ba1baae17983a31ab8

from collections import OrderedDict from pprint import pprint 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'] # names of hurricanes # 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] #Some additional functions def damage_fix(x): lst = {'M': 10**6, 'B': 10**9} try: return float(x[:-1]) * lst[x[-1]] except: return 'Damages not recorded' #Changes value to be separated with commas def damage_with_colon(x): try: return '${:,}'.format(x) except: return 'Damages not recorded' #Via versa def damage_without_colon(x): try: return float(x.translate(''.maketrans('$,',' _')).strip()) except: return 'Damages not recorded' #---------------------------------------------------- #Question 4: Prints a dictionary of each area that was affected with a value of its total count def area_count(x): all_areas = [j for i in range(len(x)) for j in x[f'Hurricane {i + 1}']['Areas Affected']] return {key: all_areas.count(key) for key in all_areas} #Question 5: Prints most affected area along with its count def most_affected_area(x): affected = sorted(area_count(x).items(), key=lambda i: i[1], reverse=True)[0] return '{}: {}'.format(affected[0], affected[1]) #Question 6. Find Hurricane that caused the most deaths. def max_deaths_caused(x): highest = max([[x[f'Hurricane {i + 1}']['Name'],x[f'Hurricane {i + 1}']['Deaths']] for i in range(len(x))], key=lambda i: i[1]) return '{}: {} Total Deaths'.format(highest[0], highest[1]) #Question 7: Print scale of mortality for each hurricane. def mortality_scale(x): scale = { 0: 0, 1: 100, 2: 500, 3: 1000, 4: 10000} scaled_list = [[x[f'Hurricane {i + 1}']['Name'],x[f'Hurricane {i + 1}']['Deaths']] for i in range(len(x))] for i in scaled_list: for j,k in scale.items(): if i[1] < k: print(f'{i[0]} has a Mortality Scale of: {j} out of 4.... Death Count {k}') break #Question 8: Prints hurricane that caused greatest damage. def max_damage(x): area_and_damage = sorted([[x[f'Hurricane {i+1}']['Name'], damage_without_colon(x[f'Hurricane {i+1}']['Damages'])] for i in range(len(x))], key= lambda i: float('inf') if isinstance(i[1], str) else i[1]) max_damage = max([value[1] for value in area_and_damage if isinstance(value[1], float)]) return 'Hurricane {}: {}'.format([i for i,j in area_and_damage if j==max_damage][0], damage_with_colon(max_damage)) #Question 9: Print scale of damage for each hurricane. def damage_scale(x): scale = { 0: 0, 1: 100000000, 2: 1000000000, 3: 10000000000, 4: 50000000000 } costs = [[x[f'Hurricane {i+1}']['Name'],x[f'Hurricane {i+1}']['Damages']] for i in range(len(x))] fixed_costs = [[i[0], damage_without_colon(i[1])] for i in costs] for number in fixed_costs: for key, value in scale.items(): if isinstance(number[1], float) and number[1] < value: print(f'{number[0]} has a Damage Scale of: {key}... Damages = {damage_with_colon(number[1])}') break def hurricanes(names, months, years, max_sustained_winds, areas_affected, damages, deaths): hurricane = {} all_hurricanes = OrderedDict() new_lst = list(zip(names, months, years, max_sustained_winds, areas_affected, damages, deaths)) for i in range(0, len(names)): hurricane = { 'Name': names[i], 'Months': months[i], 'Years': years[i], 'Max Sustained Winds': max_sustained_winds[i], 'Areas Affected': areas_affected[i], 'Damages': damage_with_colon(damages[i]), 'Deaths': deaths[i]} all_hurricanes[f'Hurricane {i + 1}'] = hurricane return all_hurricanes hurricane_dict = hurricanes(names, months, years, max_sustained_winds, areas_affected, [damage_fix(i) for i in damages], deaths) pprint(hurricane_dict) #Prints full dictionary print() pprint(area_count(hurricane_dict)) #Question 4 print() print(most_affected_area(hurricane_dict)) #Question 5 print() print(max_deaths_caused(hurricane_dict)) #Question 6 print() mortality_scale(hurricane_dict) #Question 7 print() print(max_damage(hurricane_dict))#Question 8 print() damage_scale(hurricane_dict) #Question 9

Hi Everyone,

See below the link to my GitHub repository for this project. Was a little challenging and definitely relied on some sources on the internet, but ultimately was able to complete it. Hopefully it helps anyone in need; feel free to reach out in case there are questions or concerns.

Hurricane Analysis Repo

Here is my completed challenge, doesn’t look like anybody gives feedback lol but if you want to look it is awesome!!
https://github.com/lahb2434/Hurricane_Analysis