功能测试没有按预期进行(AoC第4天的一部分)
我写了一个函数来检查数据是否正确。要求如下:
byr-(出生年份) - 四位数字;至少 1920 年,最多 2002 年。
iyr (Issue Year) - 四位数字;至少 2010 年,最多 2020 年。
eyr (Expiration Year) - 四位数字;至少 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
'''
检查提供的样本的结果应该类似于多行注释“预期结果”,但不幸的是结果始终为真。
我不知道我做错了什么 - 条件对我来说似乎很好......
回答
考虑这一行:
1920 > val > 2002
它与以下结果相同:
val < 1920 and val > 2002
这意味着 val既小于 1920,又大于 2002,这永远不会为真。