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 )"
首先,这是正确的方法吗?
其次,如果 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Python 的语言服务 解析和编译字符串,然后执行生成的 AST。
Use Python's language services to parse and compile the string, then execute the resulting AST.
用户的所有答案加在一起可用于形成唯一的二进制数(仅由零和一组成)。您可以为每个条件创建一个表(列表),该表(列表)由每个位置中答案的每个可能组合索引,存储给定条件(表示为 lambda 函数)对于该集合的值。
设置这些表后,您可以通过查找由给定答案组合索引的相应表中的值来确定任何条件是否为真。以下是如何设置的示例。
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.
因此,在根据 Ignacio 的提示进行了一些阅读之后,我想我在进行一些字符串修改后就得到了它。但是,仍然不太确定这是否是正确的方法。
因此,我的条件变量定义如下
此外,我创建变量来存储条件结果以便稍后对其进行评估
我在字符串上运行 exec
最后,我可以评估结果。
任何想法或评论都受到高度赞赏。
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
Additionally I create variable to store condition result to evaluate it later
I run exec on my string
Finally, I can evaluate result.
Any thoughts or comments highly appreciated.