Python 3布尔值

时间:2013-05-30 01:54:53

标签: python-3.x

所以,下面我得到了:return century == year // 100 + 1 or century == year / 100

但是,我不满意最后一个:

>>>in_century(2013, 20)
False

如果世纪完全等于年除以100,我如何才能使它成为唯一的? 此外,表达式的格式是或多或少正确吗?

谢谢!

以下是问题:

def in_century(year, century):
    '''(int, int) -> bool

    Return True iff year is in century.

    Remember, for example, that 1900 is the last year of the 19th century,
    not the beginning of the 20th.

    year will be at least 1.

    >>> in_century(1994, 20)
    True
    >>> in_century(1900, 19)
    True
    >>> in_century(2013, 20)
    False
    '''

1 个答案:

答案 0 :(得分:1)

那么,你的代码是这个吗?

def in_century(year, century):
    return century == year // 100 + 1 or century == year / 100

你可能不想在这里or

>>> in_century(2000, 20)
True
>>> in_century(2000, 21)
True

尝试直接计算一年的世纪,然后进行比较。

def century_from_year(year):
    return (year - 1) // 100 + 1

def in_century(year, century):
    return century_from_year(year) == century