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

发布于 2024-09-30 02:34:32 字数 623 浏览 0 评论 0原文

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

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 ,如何验证上述条件?

先感谢您。

what I am struggling with is testing predefined conditions which takes user provided parameters like in example below:

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

First of all, is this the right approach?
Secondly, how do I validate above conditions if True or False ?

Thank You in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧瑾黎汐 2024-10-07 02:34:32

使用 Python 的语言服务 解析和编译字符串,然后执行生成的 AST。

Use Python's language services to parse and compile the string, then execute the resulting AST.

云之铃。 2024-10-07 02:34:32

用户的所有答案加在一起可用于形成唯一的二进制数(仅由零和一组成)。您可以为每个条件创建一个表(列表),该表(列表)由每个位置中答案的每个可能组合索引,存储给定条件(表示为 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

All a user's answers taken together can be used to form a unique binary number (one composed of only zeros and ones). You could make a table (list) for each condition indexed by the each of the possible combinations of answer in each position store the value a given condition -- expressed as a lambda function -- would have for that set.

Once these tables are set up, you could determine whether any condition is true by looking up the value in the corresponding table indexed by a given combination of answers. Below is an example of how this might be set up.

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
说谎友 2024-10-07 02:34:32

因此,在根据 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"

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

so, after some reading based on Ignacio's tip, I think I have it after some string modifications. However, still not quite sure if this is the right approach.
So, my condition variable is defined as below

cond = """if ( 'no' is 'yes' and 'no' is 'no' ):
   result.append[1]
else:
   result.append[0]
"""

Additionally I create variable to store condition result to evaluate it later

result = []

I run exec on my string

exec(cond)

Finally, I can evaluate result.

if result[0] == 1
   print "Condition was met"
else: 
   print "Condition wasn't met"

Any thoughts or comments highly appreciated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文