Given the list of people with their parent and final years (all between 1900 and 2000 ), find the year with the most people alive.
Here is my somewhat rude decision:
def most_populated(population, single=True): years = dict() for person in population: for year in xrange(person[0], person[1]): if year in years: years[year] += 1 else: years[year] = 0 return max(years, key=years.get) if single else \ [key for key, val in years.iteritems() if val == max(years.values())] print most_populated([(1920, 1939), (1911, 1944), (1920, 1955), (1938, 1939)]) print most_populated([(1920, 1939), (1911, 1944), (1920, 1955), (1938, 1939), (1937, 1940)], False)
I am trying to find a more efficient way to solve this problem in Python . Both readability and efficiency are calculated. Moreover, for some reason, my code will not print [1938, 1939] while it should.
Update
The input is a list tuples, where the first element of the tuple is the year person was born, and the second element a tuple is the year of death.
Update 2
The end of the year (the second part of the tuple) is also considered the year of a person’s life (so if a person dies in Sept 1939 (we don’t care about a month), he actually lives in 1939, at least part of it). This should lead to a lack of results in 1939.
The best solution?
While readability is in favor of @ joran-beasley , @ njzk2 was the most efficient algorithm for more input. Thanks @ hannes-ovrén for providing the analysis in IPython notebook on Gist