使用语法/规则在Python中生成所有终端字符串?
我正在尝试从给定文件生成一定长度的所有终端字符串。例如,如果你有类似的东西
A = A B
A = B
B = 0
B = 1
那么你会得到类似的东西
0
1
0 0
0 1
1 0
1 1
这是我认为不会太困难的东西,但我陷入了困境。我目前可以读取这些值并将它们附加到字典中,并将规则存储为列表,如下所示:
{'B': [['0'], ['1']], 'A': [['A', 'B'], ['B']]}
看起来您想要做的是从非终结符之一(例如 A 或 B)开始),然后迭代每个规则。如果规则中的符号不是非终结符,您将打印或保存它,如果它是非终结符,您将用规则替换它,然后再次检查。我对如何用 Python 来做这件事感到困惑——我在这方面没有做太多事情。任何帮助将不胜感激!
I'm trying to generate all terminal strings from a given file up to a certain length. So for instance, if you have something like
A = A B
A = B
B = 0
B = 1
Then you would get something like
0
1
0 0
0 1
1 0
1 1
This is something that I thought wouldn't be overly difficult but I'm getting stuck. I can currently read the values and append them to a dictionary, with the rules being stored as a list like so:
{'B': [['0'], ['1']], 'A': [['A', 'B'], ['B']]}
It would seem like what you'd want to do is start with one of the non-terminal symbols (ex A or B) and then iterate over each rule. If the symbol in the rule isn't a non-terminal symbol, you'd print it or save it, and if it is a non-terminal symbol, you'd replace it with a rule, and then check it again. I'm stumped on how to go about doing this in Python- I haven't done much in it. Any help would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
伪代码:(
注意:“非终端单评估变体”意味着如果字符串是“AAB”,您将评估 A 中的 1,但不会评估另一个(也不会评估 B,因为它没有非终端选项)。然后您将在单独的路径中评估另一个 A - 您最终会将两个东西推入堆栈。)
请注意,在 Python 中您可以简单地使用从末尾添加/删除。堆栈的列表,和一个集合的
set()
。Pseudocode:
(Note: "non-terminal single-evaluated variant" means that if a string were "AAB", you'd evaluate 1 of the A's, but not the other (and not the B, since it has no non-terminal options). Then you'd evaluate the other A in a separate path - you'd wind up pushing two things onto the stack.)
Note that in Python you can simply use appending/removing from the end of a list for a stack, and a
set()
for a set.