虚荣板- Python

r1wp621o  于 2023-05-21  发布在  Python
关注(0)|答案(2)|浏览(77)

试图解决CS50 Python课程的问题。
卡在其中一个问题上:https://cs50.harvard.edu/python/2022/psets/2/plates/
解决了所有问题,但是“数字后面没有字母”的部分对我来说很难。
我不明白为什么我的解决方案不起作用。你知道吗?
请不要给予不同的解决方案,我读了其中的几个,我想了解哪里是我的版本中的错误。

def main():  
    plate = input("Plate: ").strip()
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
# check for non-letters and non-numbers
    if not s.isalnum():
        return False
# check for correct length    
    if len(s) < 2 or len(s) > 6:
        return False
# check for correct first two characters    
    if s[0].isdigit() or s[1].isdigit():
        return False
# check for incorrect third character if there is any    
    if len(s) > 2 and s[2] == "0":
        return False
# check for errors in 4, 5, 6 length plate nemes:
# 1. no first numeral with "0" value
    i = 0
    while i < len(s):
        if s[i].isdigit():
            if s[i] == "0":
                return False
            else:
                break
        i += 1    
# 2. no letter after numeral
    for i in range(len(s)):
        if s[i].isdigit():
            if i < len(s)-1 and s[i+1:].isalpha():
                return False
# all possible errors checked
    return True
            
main()

s[i+1:].isalpha()部分似乎永远不会执行。

lymnna71

lymnna711#

你所需要做的就是从这个语句中删除冒号。不需要检查数字后面的每个字符,只需检查下一个字符。
s[i+1].isalpha()工作。

rxztt3cl

rxztt3cl2#

使用regex可以更容易地做到这一点。下面的正则表达式很简单。它允许2到6个字母,后面可以跟不以零开始的数字。这涵盖了除了maxlength之外的所有规则,您可以在is_valid中轻松检查。

import re

m = re.compile(r'^[A-Z]{2,6}([1-9]+\d*)?$').match

def is_valid(word):
    return all((len(word)<7, m(word)))

最终,您将尝试从头开始创建自己的re.match版本,它只处理一种非常特定的情况。只要使用已经存在的re.match,停止重新发明轮子。

相关问题