Skip to content

Instantly share code, notes, and snippets.

@chrysmur
Created June 12, 2021 09:57
Show Gist options
  • Save chrysmur/88f747e1c27a4b70854cc4995b4e70ee to your computer and use it in GitHub Desktop.
Save chrysmur/88f747e1c27a4b70854cc4995b4e70ee to your computer and use it in GitHub Desktop.
Calculating the maximum number of people alive at any given time
def max_popn_year(people):
# initialize the lower and upper bounds
lower_limit = float("INF")
upper_limit = float("-INF")
# Calculate the upper and lower bounds under consideration
for person in people:
lower_limit = min(lower_limit, person.dob)
upper_limit = max(upper_limit, person.dod) + 1
#Initialize population changes in an array
popn_changes = [0] * (upper_limit - lower_limit)
# Update the population change based on dob and dod
for person in people:
popn_changes[person.dob - lower_limit] += 1
popn_changes[person.dod - lower_limit] -= 1
# initialize maximum population to 0 and population tracker to 0
max_popn = 0
population = 0
for popn_change in popn_changes:
population += popn_change
max_popn = max(population, max_popn)
return max_popn
#TEST
class Person:
def __init__(self, dob, dod):
self.dob = dob
self.dod = dod
P1 = Person(1960, 1980)
P2 = Person(1945, 1950)
P3 = Person(1965, 1987)
P4 = Person(1975, 1989)
P5 = Person(1945, 1976)
#4
people = [P1, P2, P3, P4, P5]
print(max_popn_year(people))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment