Skip to content

Instantly share code, notes, and snippets.

@jdw1996
Created January 27, 2017 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdw1996/3a73a75b0ed0677af2bef0f3c0defdc8 to your computer and use it in GitHub Desktop.
Save jdw1996/3a73a75b0ed0677af2bef0f3c0defdc8 to your computer and use it in GitHub Desktop.
An interview-style programming question.
#!/usr/bin/env python3
# Joseph Winters
# January 27, 2017
# Given a list of people with birth years and death years, all of which fall in
# the range [1900, 2000], find the year in which the most people were alive. If
# a person is alive for any part of a year, they count towards the total number
# of living people for that year.
class Person:
def __init__(self, birth_year, death_year):
self.birth_year = birth_year
self.death_year = death_year
def max_population_year(lop, begin_year, end_year):
years = [0] * (end_year - begin_year + 1)
for person in lop:
years[person.birth_year - begin_year] += 1
if person.death_year != end_year:
years[person.death_year - begin_year + 1] -= 1
max_people = 0
max_year = begin_year
curr_people = 0
for index, population_change in enumerate(years):
curr_people += population_change
if curr_people > max_people:
max_people = curr_people
max_year = begin_year + index
return max_year
if __name__ == "__main__":
lop = [
Person(1945, 1978),
Person(1940, 1968),
Person(1911, 1948),
Person(1925, 1997),
Person(1901, 1924)
]
print(max_population_year(lop, 1900, 2000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment