I am attempting to solve the following problem:
Given the list of birth dates and death dates, find the year in which the most people were alive.
Here is my code thus far:
b = [1791, 1796, 1691, 1907, 1999, 2001, 1907] # birth dates
d = [1800, 1803, 1692, 1907, 1852, 1980, 2006] # death dates
year_dict = {} # populates dict key as year, val as total living/dead
for birth in b:
year_dict.setdefault(birth,0) # sets default value of key to 0
year_dict[birth] += 1 # will add +1 for each birth and sums duplicates
for death in d:
year_dict.setdefault(death,0) # sets default value of key to 0
year_dict[death] += -1 # will add -1 for each death and sums duplicates
The following code returns:
{1791: 1, 1796: 1, 1691: 1, 1907: 1, 1999: 1, 2001: 1, 1800: -1, 1803: -1, 1692: -1, 1852: -1, 1980: -1, 2006: -1}
Now I am looking for a way to create a running sum to find which year has the most people living, example:
As we can see, the result shows 1796 had the most people alive based on the given data sets. I am having trouble getting the running sum portion which would need to take each key value, and sum it against the previous value. I have tried several different loops and enumeration, but am now stuck. Once I find the best way of resolving this, I will create a function for efficiency.
If there is a more efficient way of doing this taking into account time/space complexity, please let me know. I am trying to learn efficiency with python. I really appreciate your help!!!