You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于给定opening、closing hrs数组输出合并连续相同时段的营业时间

营业时间合并实现方案

逻辑调整思路

  • 首先把每天的开门、关门时间打包为唯一状态标识,相同状态的连续天可以合并
  • 先定义营业时间状态判定规则:
    • 开门时间等于关门时间:24小时营业
    • 开门时间大于关门时间:当日闭店
    • 其他情况:正常营业,格式为开-关
  • 遍历所有天,记录当前连续相同状态的起始天,遇到状态不同的时候就把上一段连续区间拼接进结果,更新当前状态和起始天
  • 遍历结束后把最后一段连续区间拼接进结果

完整可运行代码

# 题目给定的正确输入参数
opening_hrs = [7, 7, 7, 11, 15, 10, 17]
closing_hrs = [19, 19, 19, 19, 15, 10, 7]
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

if not opening_hrs or not closing_hrs or len(opening_hrs) != len(closing_hrs):
    print("参数错误")
    exit()

result_segments = []
# 初始化第一个区间的状态和起始天
current_state = (opening_hrs[0], closing_hrs[0])
start_day = days[0]

for i in range(1, len(days)):
    now_state = (opening_hrs[i], closing_hrs[i])
    if now_state == current_state:
        # 状态相同,继续延长当前区间
        continue
    # 状态不同,先拼接上一个区间
    if start_day == days[i-1]:
        # 区间只有一天
        day_str = start_day
    else:
        day_str = f"{start_day}-{days[i-1]}"
    # 处理状态对应的营业时间文本
    open_t, close_t = current_state
    if open_t == close_t:
        time_str = " open 24 hours"
    elif open_t > close_t:
        time_str = "-closed"
    else:
        time_str = f"-{open_t}-{close_t}"
    result_segments.append(f"{day_str}{time_str}")
    # 更新当前区间的状态和起始天
    current_state = now_state
    start_day = days[i]

# 处理最后一个区间
if start_day == days[-1]:
    day_str = start_day
else:
    day_str = f"{start_day}-{days[-1]}"
open_t, close_t = current_state
if open_t == close_t:
    time_str = " open 24 hours"
elif open_t > close_t:
    time_str = "-closed"
else:
    time_str = f"-{open_t}-{close_t}"
result_segments.append(f"{day_str}{time_str}")

# 拼接最终输出
final_output = f"Output- {' '.join(result_segments)}"
print(final_output)

输出结果

运行上述代码后输出为:

Output- Mon-Wed-7-19 Thu-11-19 Fri-Sat open 24 hours Sun-closed

和要求的目标输出完全匹配。

内容的提问来源于stack exchange,提问作者Lokesh Ramasetti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:48:01