从给定的y计算世纪

2024-04-24 05:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个条件,我必须使用return而不是print,因为如果我使用print,if条件将无法继续(如果我错了,请纠正我),现在我需要查看结果(在一些站点中,例如code-fight,它们是如何一起创建的,以检查解决方案是否正确)

def centuryFromYear(year):
    """Calculates the century for a given year: 
    Example: year 1 = 1, year 100 = 1, year 101 = 2 year 1954 = 19 etc."""
    if len(str(year)) == 1 or 2:
        return 1
    if len(str(year)) == 3:
        if year[1:3] == 0:
            return year[0]
    else:
        return year[0] + 1
    if len(str(year)) == 4:
        if year[1:4] == 0:
           return year[0] + 0
    else:
        return year[0:2] + 1

Tags: lenreturnif站点defcode解决方案条件
1条回答
网友
1楼 · 发布于 2024-04-24 05:26:41

这不是一个真正的逻辑问题,更多的是一个数学问题-不要将int转换为字符串-而是计算世纪:

def centFromYear(year):
    return (year-1)//100 +1   # substract 1 so 100 is 1 as well, floordiv by 100, add 1

for n in range(1,2000,100): # testcase centuries
    for m in range(-1,2):    # testcase -1,0,+1 to the centuries
        print(n+m, centFromYear(n+m))

输出:

^{pr2}$

相关问题 更多 >