【发布时间】:2018-02-05 16:37:35
【问题描述】:
我正在尝试使用特里树来解决这个问题:
Symbol string generator consists of two parts, a set of the start symbol and a set of rules of generation.
For example:
Start symbol: ['S'], Rules of generation: ["S → abc", "S → aA", "A → b", "A → c"]
Then, symbolic string abc can be generated because S → abc.
Symbolic string ab can be generated because S → aA → ab.
Symbolic string abc can be generated because S → aA → ac.
Now, give you a symbolic string generator and a symbolic string, and you need to return True if the symbolic string can be generated, False otherwise
Example
Given generator = ["S -> abcd", "S -> Ad", "A -> ab", "A -> c"], startSymbol = S, symbolString = “abd”, return True.
explanation:
S → Ad → abd
Given generator = ["S → abc", "S → aA", "A → b", "A → c"], startSymbol = S, symbolString = “a”, return False
我发现这个问题的关键是构建一个 trie 树。我试图写:
def build_trie(values): #value is like ['abc', 'Ad'...]
root = {}
for word in values:
current = root
is_end = False
for c in word:
if 'A' <= c <= 'Z':
vals = m[c] #m is a mapping of {'S': ['abc', 'Ad'], ...}
rs = build_trie(vals)
for k in rs:
if k not in current:
current[k] = rs[k]
else:
# stuck here...
pass
# temp = collections.defaultdict(dict)
# for d in (current[k], rs[k]):
# for k, v in d.items():
# if k in temp and k != '__end__':
# temp[k].update(v)
# else:
# temp[k] = v
# # current[k].update(rs[k])
# current[k] = temp[k]
is_end = True
else:
current = current.setdefault(c, {})
is_end = False
if not is_end:
current['__end__'] = '__end__'
return root
但是在 else 部分卡住了……还没有弄清楚如何编写这个 trie 树。有什么线索吗?
【问题讨论】:
-
我想它更多的是你试图解决的解析问题。最好为给定的语法(规则)寻找解析算法。像 LR 解析器算法这样的东西应该会有所帮助。
-
@arunk2 也许。你能提供你的代码吗?