Problem Description
The problem was initially posted here: Parse and clean up text block of store hours in Python.
Given the following multi-line string:
"""Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""
Group the consecutive weekdays by the work hours, producing the following output:
"""Mon-Thu 9:30AM-9:00PM
Fri-Sat 9:30AM-11:00PM
Sun & Hol 11:00AM-6:00PM"""
Solution
My approach is based on parsing the weekday lines, splitting by the first space and then using itertools.groupby()
to sort by the second item of every row, using the groupby
's implementation detail - it would only group the consecutive matches together:
from itertools import groupby
from operator import itemgetter
data = """Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""
# filter relevant rows with weekdays only
rows = [row.split(" ", 1) for row in data.splitlines()[1:-2]]
# group consecutive days by a time range
result = []
for time_range, group in groupby(rows, key=itemgetter(1)):
days_in_group = [item[0] for item in group]
first_day, last_day = days_in_group[0][:3], days_in_group[-1][:3]
range_end = "-" + str(last_day) if first_day != last_day else ""
result.append("{begin}{end} {time_range}".format(begin=first_day,
end=range_end,
time_range=time_range))
print("\n".join(result))
Is this the most optimal solution to the problem? Is it Pythonic? What would you improve code quality-wise?
& Hol
part of the output is difficult to infer programmatically, and in fact, you haven't done it. \$\endgroup\$