1. 程式人生 > >1028 人口普查 Python實現

1028 人口普查 Python實現

1028 人口普查(20)(20 分)

某城鎮進行人口普查,得到了全體居民的生日。現請你寫個程式,找出鎮上最年長和最年輕的人。

這裡確保每個輸入的日期都是合法的,但不一定是合理的——假設已知鎮上沒有超過200歲的老人,而今天是2014年9月6日,所以超過200歲的生日和未出生的生日都是不合理的,應該被過濾掉。

輸入格式:

輸入在第一行給出正整數N,取值在(0, 10^5^];隨後N行,每行給出1個人的姓名(由不超過5個英文字母組成的字串)、以及按“yyyy/mm/dd”(即年/月/日)格式給出的生日。題目保證最年長和最年輕的人沒有並列。

輸出格式:

在一行中順序輸出有效生日的個數、最年長人和最年輕人的姓名,其間以空格分隔。

輸入樣例:

5
John 2001/05/12
Tom 1814/09/06
Ann 2121/01/30
James 1814/09/05
Steve 1967/11/20

輸出樣例:

3 Tom John

問題分析:按年月日順序,逐一判斷是否合法,最終排序,輸出,最後一項測試超時

程式(有超時):

import operator
n = int(input())
people = []
for i in range(n):
    m = []
    a = input().split()
    m.append(a[0])
    for i in a[1].split('/'):
        m.append(int(i))
    people.append(m)       
i = 0
while i<len(people)-1:
    if people[i][1]>2014:#未出生
        people.remove(people[i])
        i-=1
    elif people[i][1]==2014:
        if people[i][2]>9:
            people.remove(people[i])
            i-=1
        elif people[i][2]==9:
            if people[i][3]>6:
                people.remove(people[i])
                i-=1
    if people[i][1]<1814:
        people.remove(people[i])
        i-=1
    elif people[i][1]==1814:
        if people[i][2]<9:
            people.remove(people[i])
            i-=1
        elif people[i][2]==9:
            if people[i][3]<6:
                people.remove(people[i])
                i-=1
    i+=1
people.sort(key = operator.itemgetter(1,2,3))
if len(people)==0:
    print(0)
else:
    print("%d %s %s"%(len(people),people[0][0],people[-1][0]))