我有plates.py的代码,有条件:
def main(): plate = input("Plate: ") if is_valid(plate): print("Valid") else: print("Invalid") def is_valid(s): if 2 <= len(s) <= 6 and s.isalnum(): if s.isalpha(): # Check if the first two characters are letters return True # Check if there are no numbers in the middle firstnum = None for c in s: if c.isdigit(): firstnum = c break if firstnum == None: return True if int(firstnum) == 0: return False ind = s.index(firstnum) pos = len(s) - ind for c in s[-pos:]: if not c.isdigit(): return False return True if __name__ == "__main__": main()
但输入50时,显示有效。应该是无效的
我想我以前遇到过这个哈佛项目和问题。尝试您的代码,突出的项目是您的“isdigit”测试。似乎要做的就是检查车牌字符串中的值是否不是从字符串中遇到第一个数字的点开始的数字。所以无论是在第一个位置还是其他位置,测试基本不起作用。
考虑到这一点,下面是一些重构的代码,可以让您更接近针对数字首次出现的个性车牌的有效性测试。
def is_valid(s):
if 2 <= len(s) <= 6 and s.isalnum():
if s.isalpha():
# Check if the first two characters are letters
return True
# Check if there are no numbers in the middle
firstnum = None
for c in s:
if c.isdigit():
firstnum = c
break
if firstnum == None:
return True
if int(firstnum) == 0:
return False
ind = s.index(firstnum)
print("First number:", firstnum, "ind:", ind)
pos = len(s) - ind
for c in s[-pos:]:
print("c:", c)
if c.isdigit() and ind < 2: # Believe you need to also check where the digits start
return False
return True
我添加了一些打印语句来提供一些简化的调试,但在重构的关键处,在确定车牌的有效性时还考虑了检查数字第一次出现的位置。
接下来,在终端进行一些快速测试。
craig@Vera:~/Python_Programs/License$ python3 vanity.py
Plate: 50
First number: 5 ind: 0
c: 5
Invalid
craig@Vera:~/Python_Programs/License$ python3 vanity.py
Plate: CD50
First number: 5 ind: 2
c: 5
c: 0
Valid
craig@Vera:~/Python_Programs/License$ python3 vanity.py
Plate: CD44FR
First number: 4 ind: 2
c: 4
c: 4
c: F
c: R
Valid
我没有详尽地测试可能的场景,但这应该突出显示哪些部分无法正常工作,并为您提供可能进一步改进的路径。