哪一年有最多的人活着

时间:2015-12-23 07:22:53

标签: python

在列表中的人(出生1,死亡1,出生2,死亡2 ......)的出生年数和死亡年数中,哪一年有最多的人活着。

我在考虑如何以正确的方式解决这个问题?我不是一个程序员而只是在玩这个问题。这是我尝试解决方案。

list1 = [1900, 1990, 1950, 1997, 1937, 1961, 1912, 1919, 1927, 1981]

initial_year = 0
alive = 0
for i in range(1900,2000):
    count = len(list1)/2
    for j in list1:
        if j%2 == 1 and j<=i:
            count = count - 1
            if count>alive:
                initial_year = i
                alive = count

return initial_year

3 个答案:

答案 0 :(得分:1)

由于你只是想尝试解决它的乐趣,这是一个低效但简单的算法:将问题分成两部分

  1. 每年确定当年活着的人数
  2. 找到活着人数最多的一年

答案 1 :(得分:0)

天真的实现如下:

lst = [1900, 1990, 1950, 1997, 1937, 1961, 1912, 1919, 1927, 1981]

birth_years = lst[0::2]
# extended slice notation means: start with the first element, end with the 
# last element, and take every second element in between
death_years = lst[1::2]
# start with the second, end with the last, and take every second

alive = 0
max_alive = (0, None)  # (num_alive, year)

for year in range(min(birth_years), max(death_years)+1):
    alive += birth_years.count(year)
    alive -= birth_years.count(year)
    if alive > max_alive[0]:
        max_alive = (alive, year)

更强大的实现可能看起来更像:

import collections

Person = collections.namedtuple("Person", "born died")
# define a structure with two attributes: "born" and "died"

people = [Person(born, died) for born, died in zip(lst[0::2], lst[1::2])]
# build a list of people

years = {y: sum(1 for p in people if p.born <= y <= p.died)
         for y in range(min(lst), max(lst)+1)}
# use a dictionary comprehension to see how many people are alive in each year

result = max(years, key=lambda k: years[k])
# use the max built-in with a key function to get the resulting year

我的直觉告诉我,对于小型列表来说,天真的实现会更快 ,但强大的实现可能会在大型列表中胜出,当然也适用于大型年份。 list.count是O(n),必须在两个半列表上运行。字典理解也是O(n),但只需要在列表的一半上运行。

答案 2 :(得分:0)

在JavaScript中

function writeOutput(inputArray) {


let n = inputArray.length;
let births = [];
let deaths = [];
let alive = 1;
let max_alive = 1;
let ix = 1;
let j = 0;


for ( i=0; i<inputArray.length ; i++){
    if ((i+2)%2 == 0){
        births.push(inputArray[i]);
    } else {
        deaths.push(inputArray[i]);
    }
}

let birthsSorted = births.sort();
let deathsSorted = deaths.sort();
let year = birthsSorted[0];
while (ix < n && j < n ){
    if (birthsSorted[ix] <= deathsSorted[ix]){
        alive += 1;
        if(alive > max_alive){
            max_alive = alive;
            year = birthsSorted[ix]
        }
        ix++;
        console.log(alive)
    } else {
        alive = alive - 1;
        j++;
    }
}


return year;   }