Python:如何验证用户自定义条件?
我现在遇到的问题是,如何测试一些预先设定的条件,这些条件需要用户提供的参数,就像下面的例子一样:
cond = "if ( 1 is yes and 2 is no ) or ( 1 is yes and 2 is no )" cond2 = "if (3 is no or 1 is no )" vars = [] lst = cond.split() lst += cond2.split() for l in lst: if l.isdigit(): if l not in vars: vars.append(l) # ... sort # ... read user answers => x = no, y = no, y = yes # ... replace numbers with input (yes or no) # ... finally I have cond = "if ( no is yes and no is no ) or ( no is yes and no is no )" cond2 = "if (yes is no or no is no )"
首先,这样做对吗?
其次,我该如何判断上面的条件是对还是错呢?
提前谢谢你。
3 个回答
0
所以,经过根据Ignacio的建议进行一些阅读后,我觉得我在对字符串进行了一些修改后,终于搞明白了。不过,我还是不太确定这是不是正确的方法。
我的条件变量定义如下:
cond = """if ( 'no' is 'yes' and 'no' is 'no' ): result.append[1] else: result.append[0] """
另外,我创建了一个变量来存储条件的结果,以便后面进行评估。
result = []
我在我的字符串上运行了exec命令。
exec(cond)
最后,我可以对结果进行评估。
if result[0] == 1 print "Condition was met" else: print "Condition wasn't met"
任何想法或评论都非常欢迎。
1
使用Python的语言服务来解析和编译这个字符串,然后执行生成的抽象语法树(AST)。
0
用户的所有回答可以组合成一个独特的二进制数字,也就是只由0和1组成的数字。你可以为每种情况创建一个表格(列表),这个表格的每一项都对应每个可能的回答组合,并存储在这个组合下某个条件的值——这个值可以用一个简单的函数来表示。
一旦这些表格建立好后,你就可以通过查找对应的表格,来判断某个条件是否成立,只需要根据给定的回答组合找到相应的值即可。下面是一个可能的设置示例。
NUM_ANSWERS = 4
NUM_COMBOS = 2**NUM_ANSWERS
NO,YES = 'no','yes'
def index(answers):
""" Convert a list of yes/no answers into binary number. """
binstr = ''.join([('1' if a is 'yes' else '0') for a in answers])
return int(binstr, 2)
def answers(index):
""" Convert binary value of number into list of yes/no answers. """
masks = [2**p for p in range(NUM_ANSWERS-1, -1, -1)]
bits = [((index & m) / m) for m in masks]
return [[NO,YES][b] for b in bits]
# condition expressions
cond_expr1 = lambda a1,a2,a3,a4: a1 is YES and a2 is NO # a3,a4 ignored
cond_expr2 = lambda a1,a2,a3,a4: (
( a1 is YES and a2 is NO ) or ( a3 is YES and a4 is NO )
)
# build tables for each condition
cond1 = []
cond2 = []
for i in range(NUM_COMBOS):
ans_combo = answers(i)
cond1.append( cond_expr1(*ans_combo) )
cond2.append( cond_expr2(*ans_combo) )
# once tables are built, you can lookup the corresponding conditional
print cond1[ index(['yes', 'no', 'no', 'yes']) ] # True
print cond2[ index(['yes', 'no', 'yes', 'no']) ] # True