我有兴趣在无序列的月份列表中找到最大的集合,它可以作为不同的连续月份的有序列表返回。
例如:
consecutive_months(["December", "January", "February", "April"])
会输出:
"December", "January", "February"
和:
consecutive_months(["February", "December", "January"])
会输出:
"December", "January", "February"
以下有效,但我很好奇是否有人对更优雅的方式有想法:
MONTHS = ["January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"]
def consecutive_months(lst_of_months):
# create two years of months to handle going from Dec to Jan
results = []
for m in set(lst_of_months):
results.append((m,MONTHS.index(m)))
results.append((m,MONTHS.index(m)+12))
results = sorted(results, key=lambda x: x[1])
# find the longest series of consecutive months
this_series = []
longest_series = []
for this_month in results:
if len(this_series) > 0:
last_month = this_series[-1]
if last_month[1] + 1 == this_month[1]:
this_series.append(this_month)
else:
this_series = [this_month]
else:
this_series = [this_month]
if len(this_series) > len(longest_series):
longest_series = [m for (m,i) in this_series]
return longest_series
这是一个带有示例输入和预期输出的 pastebin。