2017-02-18 50 views
0

鉴于两份名单的人数最多的一年:债券发现其中有积极的债券

  1. 的发行年
  2. 债券的
  3. 到期年

喜欢的东西:

issue_year = [1934, 1932, 1945, 1946, ...] 
mature_years = [1967, 1937, 1957, 1998, ...] 

在这个例子中,第一个债券的发行年为1934年,到1967年为止,而第二个债券的发行年为1932年1937年到期,等等。

我试图解决的问题是找到活跃债券数量最多的年份。

这是我到目前为止。这是所有债券活跃的年份。

L1=[1936,1934,1937] 
L2=[1940,1938,1940] 

ctr=0 
for i in range(len(L1)): 
    j=i 
    L3=list(range(L1[i],L2[j])) 
    if ctr==0: 
     tempnew=L3 
    else: 
     tempnew=list(set(L3) & set(tempnew)) 

    ctr = ctr+1 

这里tempnew是所有债券的所有活跃年数的交集。但是,可能发生的情况是所有活动年份的交集可能都是空的。例如,如果债券1从1932年到1945年是活跃的,债券2从1947年到1960年是活跃的。

有人可以帮忙吗?

+2

到目前为止你已经尝试了什么? –

+0

@Kahirul Thanx回复。这是我的代码,它将把所有债券的所有活跃年份交叉在一起。对于范围(len(L1))中的i,L2 = [1940,1938,1937] L2 = [1940,1938,1940] ctr = 0 L3 =列表(范围(L1 [i ],L2 [j]的)) #PRINT L3 如果CTR == 0: tempnew = L3 否则: tempnew =列表(集(L3)及设定(tempnew)) #临时= tempnew CTR = ctr + 1' – jayant

回答

0

下面是我认为符合您的要求的一些代码。它的工作原理是使用zip扫描issuemature年列表。然后它填写一个关键字都是活跃年份的字典,其值是当年活跃的债券数量。最后,转储所有这些都活跃债券的最大数量的岁月:

代码:

def add_active_years(years, issue, mature): 
    for year in range(issue, mature+1): 
     years[year] = years.get(year, 0) + 1 

# go through the lists and calculate the active years 
years = {} 
for issue, mature in zip(L1, L2): 
    add_active_years(years, issue, mature) 

# now reverse the years dict into a count dict of lists of years 
counts = {} 
for year, count in years.items(): 
    counts[count] = counts.get(count, []) + [year] 

# show the result 
print(counts[max(counts.keys())]) 

样本数据:

L1 = [1936,1934,1937] 
L2 = [1940,1938,1940] 

结果:

[1937, 1938] 
+0

谢谢你的帮助。 – jayant

+0

你非常欢迎。然而,在SO上,说谢谢的最好方法是upvote *任何*您认为有用的答案(或问题)。即使在你没有问的问题上也是如此。干杯。 –