开发者

Generating all terminal strings in Python with grammar/rules?

开发者 https://www.devze.com 2023-04-04 08:38 出处:网络
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

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 ru开发者_开发技巧le, 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!


Pseudocode:

for each symbol:
    push that symbol onto the stack

while an item X can be popped off the stack:
    if X contains a non-terminal
        calculate each possible result with variation of the leftmost nonterminal
        if that variation is lower than the max length
             push it to the stack
    else
        add the popped X to a set Q of results (for de-duping)

print out the contents of Q (sorted, if so desired)

(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号