我正在尝试学习Python,在这种情况下我正在解决一个问题。 该问题旨在检查一串字符是否:
据我了解,只有两部分代码导致了问题,因此我仅提出这两个问题:
我的代码如下:
def number_end_plate(s):
if s.isalpha():
return False
else:
number = ""
for char in s:
if char.isnumeric():
number = number + char
else:
number = number
result = number.startswith("0")
return(result)
# Function "number_end_plate" checks if the numbers starts with zero. If "True" then this will be rejected in the above function
def numbers_after_letter(s):
if s.isalpha():
return True
elif len(s) == 4 and s == s[3:4].isnumeric():
return True
elif len(s) == 4 and s == s[3:3].isalpha() and s == s[4:4].isnumeric():
return True
elif len(s) == 5 and s == s[3:5].isnumeric():
return True
elif len(s) == 5 and s == s[3:4].isalpha() and s == s[5:5].isnumeric():
return True
elif len(s) == 5 and s == s[3:3].isalpha() and s == s[4:5].isnumeric():
return True
elif len(s) == 6 and s == s[3:6].isnumeric():
return True
elif len(s) == 6 and s == s[3:3].isalpha() and s == s[4:6].isnumeric():
return True
elif len(s) == 6 and s == s[3:4].isalpha() and s == s[5:6].isnumeric():
return True
elif len(s) == 6 and s == s[3:5].isalpha() and s == s[6:6].isnumeric():
return True
#Function checks if the numbers (if any) are always at the end of the string
我未通过以下测试,我不明白为什么结果是“
Invalid
”:
您的代码有很多问题和不一致之处,但您问题的答案就在这个函数中:
def number_end_plate(s):
if s.isalpha():
return False
else:
number = ""
for char in s:
if char.isnumeric():
number = number + char
else:
number = number
result = number.startswith("0")
return(result)
return 语句在 for 循环内缩进,因此只会迭代一次。目前还不清楚它应该检查什么。看起来车牌以数字结尾,但你这样使用它:
and number_end_plate(s) == False
- 所以,显然以数字结尾的车牌应该总是无效的?
这与您提供的描述不符。然后你有一个非常复杂的函数,据说可以检查所有数字是否都在字符串的末尾。
代码的其他问题包括间距(代码之间的垂直间距,以及更糟糕的不一致缩进)、拼写错误(名称中)、函数工作方式不一致(有时简洁并直接返回结果,有时冗长,如果-陈述),也许还有更多超出我上面指出的逻辑错误。
修复这些问题,但保持程序的整体结构(仍然非常冗长),你最终会得到这样的结果:
import string
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
return valid_length(s) and starts_alpha(s) and no_punctuation(s) and number_end_plate(s)
def valid_length(s):
return 2 <= len(s) <= 6
def starts_alpha(s):
return s[0:2].isalpha()
def no_punctuation(s):
return not any(character in string.punctuation for character in s)
def number_end_plate(s):
found_number = False
for ch in s:
if ch.isdigit():
if not found_number:
if ch == '0':
# the first number cannot be a 0
return False
found_number = True
else:
if found_number:
# if there's something that's not a number after a number
return False
# at this point, the text is valid
return True
main()