我正在尝试创建一个函数,根据某些条件检查字符串的有效性。
条件:
传入的任何内容都会导致设置为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,则因此有效设置为真正。如果有人能帮助我写下我的想法,那将是非常感激的代码。
这里有一些输出输出:
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
答案 0 :(得分:1)
这将解析您使用正则表达式编写的所有输入,但请记住,算术运算是由无上下文语法生成的,因此您无法找到与所有现有操作匹配的正则表达式(仅对常规语言有效) (例如(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