python - 功能测试没有按预期进行(AoC 第 4 天的一部分)

我写了一个函数来检查数据是否正确。 要求如下:

byr-(出生年份)——四位数字;至少 1920 年,最多 2002 年。

iyr(发行年份)——四位数;至少 2010 年,最多 2020 年。

eyr(过期年份)——四位数;至少 2020 年,最多 2030 年。

def check_byr_iyr_eyr(line):
    statement = True
    if line[:3] == "byr":
        if (len(line[line.index(':')+1:]) != 4 or
        1920 > int(line[line.index(':')+1:]) > 2002 ):
            statement = False
    elif line[:3] == "iyr":
        if (len(line[line.index(':')+1:]) != 4 or
        2010 > int(line[line.index(':')+1:]) > 2020 ):
            statement = False
    elif line[:3] == "eyr":
        if (len(line[line.index(':')+1:]) != 4 or
        2020 > int(line[line.index(':')+1:]) > 2030 ):
            statement = False
    return statement


list = ['byr:1919', 'iyr:2010', 'eyr:2021', 'iyr:2019', 'iyr:1933',
        'byr:1946', 'iyr:1919', 'eyr:2005']

for i in list:
    print(check_byr_iyr_eyr(i))

'''
    expected result:
        False
        True
        True
        True
        False
        True
        False
        False
'''

检查提供的样本的结果应该像多行注释中的“预期结果”,但不幸的是,结果总是 True。

我不知道我做错了什么 - 条件对我来说似乎很好......

最佳答案

考虑这一行:

1920 > val > 2002

与以下结果相同:

val < 1920 and val > 2002

这意味着 val 小于 1920 又大于 2002,这永远不可能是真的。

https://stackoverflow.com/questions/65584294/

相关文章:

android-studio - flutter SDK 不完整

python - PyTorch 张量的零对角线?

python - 从明亮的彩条下发现图像

c++ - 在模板参数中,哪些规则允许编译器推断数组的项数?

reactjs - 接口(interface)命名约定(接口(interface)名称与组件名称冲突

powershell - 在 switch 语句中分配变量

javascript - JavaScript 中的常量数组

c++ - fatal error LNK2019 C++,Unreal Engine Build

reactjs - React 项目中的 URI 格式错误 - 使用 Parcel Bundler

c++ - C++ 是否包含包含的头文件包含的所有头文件?