python:如何验证用户定义的条件?

时间:2010-10-30 16:53:57

标签: python validation conditional-statements

我正在努力的是测试预定义条件,这些条件采用用户提供的参数,如下例所示:

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 )" 

首先,这是正确的方法吗? 其次,如果判断为True还是False,我如何验证上述条件?

提前谢谢你。

3 个答案:

答案 0 :(得分:1)

使用Python's language services解析并编译字符串,然后执行生成的AST。

答案 1 :(得分: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"

高度赞赏任何想法或评论。

答案 2 :(得分:0)

所有用户的答案一起用于形成唯一的二进制数(一个仅由零和一个组成)。你可以为每个条件的每个条件索引建立一个表(列表),每个位置的每个可能的答案组合存储一个给定条件的值 - 表示为lambda函数 - 对于该集合将具有该值。

设置这些表后,您可以通过查找由给定答案组合索引的相应表中的值来确定是否有任何条件成立。以下是如何设置此功能的示例。

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