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

不使用def、类、循环时,Python判断日期对应季节是否有更优实现?

简化实现方案

核心思路为将月份字符串映射为数值,先完成输入合法性校验,再按季节日期区间直接判断,全程不使用函数、类、循环结构,逻辑远较原版本简洁。

完整实现代码

input_month = input()
input_day = int(input())

# 月份转数字映射,非法月份返回0
month_num = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6,
             'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':12}.get(input_month, 0)

# 输入合法性校验
max_day = 31 if month_num in (1,3,5,7,8,10,12) else 30 if month_num in (4,6,9,11) else 28 if month_num ==2 else 0
if month_num == 0 or input_day <=0 or input_day > max_day:
    print('Invalid')
else:
    # 按边界判断季节,和原代码逻辑一致(已修正原代码5月判断的笔误)
    if (month_num ==3 and input_day >=20) or (4<=month_num<=5) or (month_num ==6 and input_day <=20):
        print('Spring')
    elif (month_num ==6 and input_day >=21) or (7<=month_num<=8) or (month_num ==9 and input_day <=21):
        print('Summer')
    elif (month_num ==9 and input_day >=22) or (10<=month_num<=11) or (month_num ==12 and input_day <=20):
        print('Autumn')
    else:
        print('Winter')

代码说明

  • 月份映射字典直接完成合法月份校验,非法月份会返回0,后续直接判定为无效
  • 合法性校验一次性覆盖非法月份、日期小于等于0、日期超出对应月份最大天数三种无效场景
  • 季节判断用组合条件替代原版本的多分支逐个枚举,逻辑清晰且代码量大幅降低
  • 已修正原代码中5月仅判定31日为春季的笔误,若需保留原笔误逻辑可调整春季判断条件即可

内容的提问来源于stack exchange,提问作者Derek Pruitt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:36:01