CS50 个性化车牌可检测字母中的数字

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

我编写了一个代码来验证汽车的车牌,并且有一些条件可以实现此目的:

  • 第一个数字不应该是
    0
  • 字母之间不应有任何数字(
    AAA12
    可以,但
    AA2AAA
    则不行。)
  • 应该以两个字母开头
  • 字符数必须在 2 - 6 个字母之间
  • 仅允许使用字母和数字
def is_valid(s):
    s = s.lower()
    if len(s) >= 2 and len(s) <= 6 and s[0] != 0 and s[0:2].isalpha():
        if s.isalpha():
            return True
        elif s.isalnum():
            for sq in s.split():
                for w in sq:
                    if w.isdigit():
                        x = sq.index(w)
                        try:
                            if s[w:].isalpha():
                                return False
                            else:
                                return True
    
                        except:
                            return True

所以我的代码以正确的方式执行了大多数这些条件,但是当我输入例如

HL23P2
,我希望得到
False
,但它返回
True

为什么会返回

False
?因为我不能在字母之间有数字,只有当它像例如
HEL23

但是如何检测字母之间的数字?

python cs50
3个回答
0
投票

我认为,这个没有正则表达式的解决方案就可以了:

def is_valid(s):
    meetNumber = False
    if len(s) >= 2 and len(s) <= 6 and s[0:2].isalpha():
        for i in range(2, len(s)):
            if s[i].isnumeric():
                meetNumber = True
            elif meetNumber == True:
                return False
        return True
    else:
        return False

print(is_valid(input()))

0
投票

尝试类似:

import re

def is_valid(s):
    return bool(re.search(r'^(?=.{2,6}$)[A-Z]{2,}\d*$', s))

print([is_valid(el) for el in ['AAA12', 'AA2AAA', 'HL23P2', 'HEL23']])

打印:

[True, False, False, True]

使用的正则表达式意思是:

  • ^
    - 起始字符串;
  • (?=.{2,6}$)
    - 正向预测精确匹配 2-6 个字符,直到结束字符串锚点(满足您总共 2-6 个字符的要求);
  • [A-Z]{2,}
    - 2+ 大写字母(满足您的要求,以至少 2 个字母字符开头);
  • \d*
    - 0+ 位数字(满足您的要求,字符之间没有数字,但只能在末尾);
  • $
    - 端弦锚。

0
投票
def is_valid(s):
    if 2 <= len(s) <= 6 and s[0:2].isalpha() and s.isalnum():
        for item in s:
            if item.isdigit():
                pos = s.index(item)
                if s[pos:].isdigit() and int(item) != 0:
                    return True
                else:
                    return False

        return True
© www.soinside.com 2019 - 2024. All rights reserved.