查找使用Python的人数最多的年份 [英] Find the year with the most number of people alive in Python

查看:233
本文介绍了查找使用Python的人数最多的年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个列表,列出他们的出生和结束年龄(都在 1900 2000 之间)人数最多的一年。

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 is my somewhat brute-force solution:

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)

我正在尝试找到更多的ef在 Python 中解决此问题的有效方法。两者-可读性效率计数。而且,由于某种原因,我的代码不会打印 [1938,1939] ,而应该打印。

I'm trying to find a more efficient way to solve this problem in Python. Both - readability and efficiency counts. Moreover, for some reason my code won't print [1938, 1939] while it should.

更新

输入是元组的列表,其中元组的第一个元素是 year 人出生时的年份,元组的第二个元素是死亡年份。

Input is a list of tuples, where first element of a tuple is a year when person was born, and second element of a tuple is the year of death.

更新2

结束年份(元组的第二部分)计数以及该人所在的年份还活着(所以,如果这个人死于1939年9月的(我们不在乎这个月),那么他实际上在1939年还活着,至少是其中一部分)。那应该可以解决1939年结果缺失的问题。

End year (2nd part of tuple) counts as well as a year of the person being alive (so If the person dies in Sept 1939 (we don't care about the month), he is actually alive in 1939, at least part of it). That should fix the 1939' missing in results.

最佳解决方案?

虽然可读性支持 @ joran-beasley ,但对于较大的输入, @ njzk2 。感谢@hannes-ovrén在

While readability counts in favor of @joran-beasley, for bigger input most efficient algorithm was provided by @njzk2. Thanks @hannes-ovrén for providing analysis in IPython notebook on Gist

推荐答案

>>> from collections import Counter
>>> from itertools import chain
>>> def most_pop(pop):
...     pop_flat = chain.from_iterable(range(i,j+1) for i,j in pop)
...     return Counter(pop_flat).most_common()
...
>>> most_pop([(1920, 1939), (1911, 1944), (1920, 1955), (1938, 1939)])[0]

这篇关于查找使用Python的人数最多的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆