Section #8 Solutions

Task 1: Find Missing Friends

                    
                        def find_missing_friends(filename):
   """
   Given a JSON file, find and print the names of
   the friends who are mentioned but are missing from the network.


   >>> find_missing_friends("data.json")
   Michael
   Koa
   Haipeng
   Eli
   Kavita
   William
   Jose
   Nika
   """
   with open(filename, "r") as file:
       input_dict = json.load(file)
   data = input_dict["network"]
   missing_friends = []
   for person in data:
       person_data = data[person]
       persons_friends = person_data["friends"]
       for friend in persons_friends:
           name = friend["name"]
           if name not in data and name not in missing_friends:
               print(name)
               missing_friends.append(name)
                    
                

Task 2: Calculate Total Friendship Years

            
def calculate_total_years(filename, person):
    """
    Given a JSON file and person,
    calculate and print the total number of years a given person has been friends with their friends.


    >>> calculate_total_years("data.json", "Sabino")
    Sabino has a total of 10 years of friendship.


    >>> calculate_total_years("data.json", "Langston")
    Langston is not in the network.
    """


    with open(filename, "r") as file:
        input_dict = json.load(file)
    data = input_dict["network"]


    # Check if the person is in the network
    if person not in data:
        print(f"{person} is not in the network.")
        return


    # Calculate the total years of friendship
    total_years = 0
    person_dict = data[person]
    for friend in person_dict["friends"]:
        total_years += friend["years_friends"]


    print(f"{person} has a total of {total_years} years of friendship.")