Skip to main content
 首页 » 编程设计

python之基于某些条件的字符串有效性

2025年05月04日19落叶无声

我正在尝试创建一个函数来根据某些条件检查字符串的有效性。

条件:

  1. 将 0-9 之间的数字作为字符串(例如“1”)传递会将 valid 设置为 True。
  2. 将 0-9 + * 中的数字作为字符串(例如“9*”、“2*”)传递会将 valid 设置为 True。
  3. 传递括号中包含 0-9 + * + 0-9 数字(例如“(9*1)”、“(1*3)”)的字符串会将 valid 设置为 True。
  4. 在方括号中传递上述任何一项 [except 2] + * + 上述任何一项 [except 2] 会将 valid 设置为 True ex。 ((9*1)*1)

传入的任何其他内容都会导致将 valid 设置为 False。

这是我所做的:

CHARS = "*" 
NUMBERS = "0123456789" 
 
def validity(s): 
    valid = False 
    # Condition 1 
    if s in NUMBERS: 
        valid = True 
    # Condition 2 
    elif s in [c1 + CHARS for c1 in NUMBERS]: 
        valid = True 
    # Condition 3 
    elif s in ['(' + c1 + CHARS + c2 + ')' for c1 in NUMBERS for c2 in NUMBERS]: 
        valid = True 
    return valid 

我的条件 1-3 可以正常工作。然而,我被困在条件 4 上。

我对要做什么有一个粗略的想法,但我在如何使用代码实现我的想法方面遇到了麻烦。

这是我的想法。如果传入条件 4,例如。 ((9*1)*1) 在 * 符号左边的字符串上运行有效性,在 * 符号右边的字符串上运行有效性,如果两者都为 True 则条件为 True,因此 valid 设置为真的。如果有人能帮我用代码写下我的想法,那将不胜感激。

这里有一些输入和输出:

validity('1') # Condition 1 
True 
validity('9') # Condition 1 
True 
validity('10') # Doesn't satisfy any of the conditions 
False 
validity('1*') # Condition 2 
True 
validity('4*') # Condition 2 
True 
validity('9*') # Condition 2 
True 
validity('10*') # Doesn't satisfy any of the conditions 
False 
validity('(3*4)') # Condition 3 
True 
validity('(3*9)') # Condition 3 
True 
validity('(4*9)') # Condition 3 
True 
validity('(10*9)') # Doesn't satisfy any of the conditions 
False 
validity('(3*2)*(3*1)') # Condition 4 
True 
validity('(3*2)*8') # Condition 4 
True 
validity('(3*2)*z') # Doesn't satisfy any of the conditions 
False 

请您参考如下方法:

这将解析您使用正则表达式编写的所有输入,但请记住,算术运算是由上下文无关语法生成的,因此您不会找到匹配所有现有操作的正则表达式(仅对常规语言有效)(例如(3*(3*2))*(3*1)、(3*(3*(3*2)))*(3*1) 和依此类推),您将需要构建不同的。

import re 
 
parser1 = re.compile("[0-9]\\*?$") 
parser3 = re.compile("\\([0-9]\\*[0-9]\\)$") 
parser4 = re.compile("(\\([0-9]\\*[0-9]\\)|[0-9])\\*(\\([0-9]\\*[0-9]\\)|[0-9])$") 
 
def validity(s): 
    valid = False 
 
    # Condition 1 and 2 
    if parser1.match(s): 
        return True 
    # Condition 3 
    if parser3.match(s): 
        return True 
    # Condition 4 
    if parser4.match(s): 
        return True 
 
    return False 
 
print validity('1') # Condition 1 
print validity('9') # Condition 1 
print validity('10') # Doesn't satisfy any of the conditions 
print validity('1*') # Condition 2 
print validity('4*') # Condition 2 
print validity('9*') # Condition 2 
print validity('10*') # Doesn't satisfy any of the conditions 
print validity('(3*4)') # Condition 3 
print validity('(3*9)') # Condition 3 
print validity('(4*9)') # Condition 3 
print validity('(10*9)') # Doesn't satisfy any of the conditions 
print validity('(3*2)*(3*1)') # Condition 4 
print validity('(3*2)*8') # Condition 4 
print validity('(3*2)*z') # Doesn't satisfy any of the conditions 

这里的输出是:

True 
True 
False 
True 
True 
True 
False 
True 
True 
True 
False 
True 
True 
False