繁体   English   中英

使用 Python 计算两年之间的闰年数及其平均值

[英]Count the number of leap years between two years and their average using Python

您如何计算闰年的数量并使用以下 python 脚本计算它们的平均值?

start = int(input("Enter start year: "))
end = int(input("Enter end year: "))

if start <= end:
    leap_years = [str(x + start) for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
    leap_years[-1] += "."
    print(f"Here is a list of leap years between {start} and {end}:\n{(', '.join(leap_years))}")

from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)

print(len(leap_years))
print(avg_leap_year)

请让我知道是否可以改进此脚本以减少冗余。

谢谢!

这是一个简单的解决方案:

from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM