我写了一个函数来检查数据是否正确。 要求如下:
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,这永远不可能是真的。
关于python - 功能测试没有按预期进行(AoC 第 4 天的一部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65584294/