面试题答案
一键面试def day_of_year(year, month, day):
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days_in_month[1] = 29
total_days = 0
for i in range(month - 1):
total_days += days_in_month[i]
total_days += day
return total_days
代码优化思路
-
提高可读性:
- 增加注释:在关键代码处添加注释,例如在判断闰年和计算总天数的地方,说明代码的作用。
- 函数命名:使用更具描述性的函数名,如
calculate_day_of_year
,让代码的功能一目了然。 - 变量命名:对于
days_in_month
可以改为days_per_month
,增强变量含义的清晰度。
-
提高执行效率:
- 减少重复计算:可以将闰年判断逻辑提取到一个单独的函数中,这样如果在其他地方也需要判断闰年,直接调用该函数即可,避免重复代码。
- 数据结构优化:如果频繁调用该函数,可以考虑使用缓存机制,例如
functools.lru_cache
来缓存已经计算过的结果,减少重复计算。
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def calculate_day_of_year(year, month, day):
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
days_per_month[1] = 29
total_days = 0
for i in range(month - 1):
total_days += days_per_month[i]
total_days += day
return total_days
这里通过将闰年判断逻辑提取到is_leap_year
函数中,使calculate_day_of_year
函数更加简洁,提高了代码的可读性和可维护性。