月の順序付けられていないリストで最大のセットを見つけることに興味があります。これは、連続した別個の月の順序付けられたリストとして返すことができます。
例えば:
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
これは、サンプル入力と予想される出力を含むペーストビンです。