我编写了一个函数来检查数据是否正确。所需经费如下:
(出生年份)-四位数;至少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
'''检查提供的样本的结果应该类似于多行注释“预期结果”,但不幸的是,结果总是真实的。
我不知道我做错了什么-条件对我来说似乎很好.
发布于 2021-01-05 18:21:06
一个优雅的解决方案,使用太多的if语句并不枯燥(不要重复自己):
def check_byr_iyr_eyr(line):
# split the string on the colon to get the two parts
prefix, year = line.split(':')
# getting around python's lack of case statements with a dictionary
cases = {
'byr': {'min': 1920, 'max': 2002},
'iyr': {'min': 2010, 'max': 2020},
'eyr': {'min': 2020, 'max': 2030},
}
# get the corresponding min and max and check if the year is inclusively between them
# (note the <= instead of <)
return cases[prefix]['min'] <= int(year) <= cases[prefix]['max']
data = ['byr:1919', 'iyr:2010', 'eyr:2021', 'iyr:2019', 'iyr:1933',
'byr:1946', 'iyr:1919', 'eyr:2005']
for i in data:
print(check_byr_iyr_eyr(i))输出:
False
True
True
True
False
True
False
False发布于 2021-01-05 18:16:56
考虑到这一行:
1920 > val > 2002其结果与以下情况相同:
val < 1920 and val > 2002这意味着val既不到1920年,又大于2002年,这是不可能的。
发布于 2021-01-05 18:18:52
您的功能有两个问题:
string in line。它简单得多,可读性强得多。如wim所提到的,
5 > x > 7等价于and语句。因为x不能同时小于5和大于7,所以这永远不是真的。做x > 7 or x < 5代替.下面是具有正确输出的更正代码:
def check_byr_iyr_eyr(line):
statement = True
if "byr" in line:
if (len(line[line.index(':')+1:]) != 4 or
int(line[line.index(':')+1:]) > 2002 or
int(line[line.index(':')+1:]) < 1920):
statement = False
elif "iyr" in line:
if (len(line[line.index(':')+1:]) != 4 or
int(line[line.index(':')+1:]) > 2020 or
int(line[line.index(':')+1:]) < 2010):
statement = False
elif "eyr" in line:
if (len(line[line.index(':')+1:]) != 4 or
int(line[line.index(':')+1:]) > 2030 or
int(line[line.index(':')+1:]) < 2020):
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
'''看看elegant的答案,一个更优雅的解决方案!
https://stackoverflow.com/questions/65584294
复制相似问题