I'm interested in finding the largest set in an unordered list of months, that can be returned as an ordered list of distinct, consecutive months.
For example:
consecutive_months(["December", "January", "February", "April"])
Would output:
"December", "January", "February"
And:
consecutive_months(["February", "December", "January"])
Would output:
"December", "January", "February"
The following works but I'm curious if anyone has ideas for a more elegant way:
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
Here is a pastebin with sample inputs and expected outputs.
Here are two working approaches from a friend who also looked at the problem. The first is performant and uses the modulo operator so that the list doesn't need to copied onto itself.
The second is a clever one-liner:
Both algorithms return the expected results for the test data. Thanks AV!