刚刚写完 CS50 下的 Vanity Plates 作业。想知道是否有办法提高效率

问题描述 投票:0回答:1

代码有效,我已经提交了。然而,我很难让它变得更简洁。

def main():

    plate = input("Plate: ")
    if length(plate) and check_firstnum(plate):
        print("Valid")
    else:
        print("Invalid")

def length(s):

    if (2 <= len(s) <= 6) and s[0:2].isalpha() and s.isalnum():
        return True
    else:
        return False

def check_firstnum(n):

    for char in n:
        if char.isdigit():
            index = n.index(char)
            if n[index:].isdigit() and char != 0:
                return True
            else:
                return False
    return True

main()
python cs50
1个回答
0
投票

对于如此琐碎的事情,可能不值得为单独的测试编写离散函数。

请注意 str.isdigitstr.isdecimal 之间的区别,在这种情况下,后者是首选。

只需使用像这样的“直线”代码即可:

def is_valid(plate):
    if not 2 <= len(plate) <= 6:
        return False
    if not plate[:2].isalpha():
        return False
    if not plate.isalnum():
        return False
    for i, c in enumerate(plate[2:], 2):
        if c.isdecimal():
            if c == "0":
                return False
            if not plate[i:].isdecimal():
                return False
            break
    return True

if __name__ == "__main__":
    plate = input("Plate: ")
    print("Valid" if is_valid(plate) else "Invalid")
© www.soinside.com 2019 - 2024. All rights reserved.