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

后端 未结 9 2118
梦谈多话
梦谈多话 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:47

    How about this one:

    def max_pop(pop):
        p = 0; max = (0,0)
        for y,i in sorted(chain.from_iterable([((b,1), (d+1,-1)) for b,d in pop])):
            p += i
            if p > max[1]: max=(y,p)
        return max
    

    It's not affected by the year span but is nlogn in the |pop| (unless you'd roll out a radix sort which would be ~ 10n for a thousand year span and should be faster for |pop|>1000 ). Can't have both. A very general solution would have to scan first and decide which algo to use based on measured year span and |pop|.

提交回复
热议问题