Find the year with the most number of people alive in Python

后端 未结 9 2119
梦谈多话
梦谈多话 2020-12-14 20:48

Given a list of people with their birth and end years (all between 1900 and 2000), find the year with the most number of people alive.

Here

9条回答
  •  不知归路
    2020-12-14 21:46

    Another solution I just though of:

    • Create 2 tables, birthdates and deathdates.
    • Accumulate birth dates and death dates in those tables.
    • Browse those tables to accumulate the number of alive people at the time.

    Grand total complexity is O(n)

    Implementation

    from collections import Counter
    
    def most_populated(population, single=True):
        birth = map(lambda x: x[0], population)
        death = map(lambda x: x[1] + 1, population)
        b = Counter(birth)
        d = Counter(death)
        alive = 0
        years = {}
        for year in range(min(birth), max(death) + 1):
            alive = alive + b[year] - d[year]
            years[year] = alive
        return max(years, key=years.get) if single else \
               [key for key, val in years.iteritems() if val == max(years.values())]
    

    Better

    from collections import Counter
    from itertools import accumulate
    import operator
    
    def most_populated(population, single=True):
        delta = Counter(x[0] for x in population)
        delta.subtract(Counter(x[1]+1 for x in population))
        start, end = min(delta.keys()), max(delta.keys())
        years = list(accumulate(delta[year] for year in range(start, end)))
        return max(enumerate(years), key=operator.itemgetter(1))[0] + start if single else \
               [i + start for i, val in enumerate(years) if val == max(years)]
    

提交回复
热议问题