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

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

    1. Just put the birth and death years into a dict. If it is birth, increase the value by 1. or vice versa.
    2. Sort the dict by keys and iterate by reading the current number of the alive people.
    3. Follow the 'maxAlive' an 'theYear' to get the first year with the highest number

      years = {} 
      
      for p in people:
          if p.birth in years:
              years[p.birth] += 1
          else:
              years[p.birth] = 1
      
          if p.death in years:
              years[p.death] -= 1
          else:
              years[p.death] = -1
      
      alive = 0
      maxAlive = 0
      theYear = people[0].birth
      for year in sorted(years):
          alive += years[year]
          if alive > maxAlive:
              maxAlive = alive
              theYear = year
      

提交回复
热议问题