【发布时间】:2010-11-22 09:42:36
【问题描述】:
是否有一种算法可以根据给定的上下文无关文法生成所有字符串?
【问题讨论】:
-
我认为你应该更明确地说明你想在这里做什么。例如,对于大多数 CFG,一个简单的算法可能不会终止。
-
一般来说,这不是一个无限集吗?这样的算法必须是 O(∞)
标签: algorithm compiler-construction computation-theory
是否有一种算法可以根据给定的上下文无关文法生成所有字符串?
【问题讨论】:
标签: algorithm compiler-construction computation-theory
Leonardo 的回答在技术上是正确的;没有终止算法会返回一般 CFG 的词集,因为该集通常是无限的。
但是有些算法会为 CFG 生成一个单词序列,每个匹配语法的单词都会“最终”出现。其中之一应该足以满足您的目的。用带有yield 的语言(例如 Python)编写其中的一个相当容易。
这样一个算法的草图(恐怕是相当无望的伪代码):
generate(g):
if g is empty:
yield ""
otherwise if g is a terminal a:
yield "a"
otherwise if g is a single nonterminal:
for c in every construction of g:
start a generator for generate(c)
until all generators are exhausted:
looping over each nonexhausted generator gen:
yield "a" where a = next(gen)
otherwise if g is a pair of symbols m and n:
for c in every construction of m:
start a generator in set 1 for generate(c)
for d in every construction of m:
start a generator in set 2 for generate(d)
until all in set 1 or all in set 2 are exhausted:
loop over all pairs gen1,gen2 of nonexhausted in set 1 and set 2:
yield "a b" where a = next(gen1) and b = next(gen2)
假设语法已被转换,使得每个构造为零到两个终结符,这将对语法的所有分析树的树进行广度优先搜索。 BFS 是必要的,因为任何给定子树的大小都可能是无限的——DFS 可能会一直向下看其中一个。
等待给定任何解析树实现的时间和内存成本可能是任意的,但对于该解析树来说是有限的。
【讨论】:
问:有没有一种算法可以根据给定的上下文无关文法生成所有字符串?
A:不,语法是一组定义单词的规则,某些语法会生成一定数量的单词,但绝大多数会生成无穷多的单词,所以不,没有算法可以从给定语法生成所有字符串
【讨论】: