[英]Python - Tree Search
I am searching for the most efficient tree search implementation in python.我正在寻找 python 中最有效的树搜索实现。 I give the tree search a sequence of length n and it should detect if the branches are already created, or if this is not the case, generate the branches.我给树搜索一个长度为 n 的序列,它应该检测是否已经创建了分支,或者如果不是这种情况,则生成分支。
Example:例子:
i1: Sequence 1[0.89,0.43,0.28] i1:序列 1[0.89,0.43,0.28]
0.89 check
|
0.43 check
|
0.28 check(last branch, last number of sequence == found)
i2: Sequence 2[0.89,0.43,0.99] i2:序列 2[0.89,0.43,0.99]
0.89 check
|
0.43 check
| |
0.28 missing(Creating new branch) 0.99
Considering the order within the sequences is important.考虑序列内的顺序很重要。
The goal is to keep track of a huge range of sequence (seen, unseen).目标是跟踪大范围的序列(可见、不可见)。
Has anyone ideas?有没有人的想法?
You could use an infinitely nested collections.defaultdict
for this.您可以为此使用无限嵌套的collections.defaultdict
。 The following function will create a defaultdict
, that whenever the requested value is not present will call the same function again, creating another defaultdict
, ad infinitum.以下函数将创建一个defaultdict
,每当请求的值不存在时,它将再次调用相同的函数,创建另一个defaultdict
,无限期。
import collections
nested = lambda: collections.defaultdict(nested)
dic = nested()
Now, you can add the sequences to the nested defaultdict.现在,您可以将序列添加到嵌套的 defaultdict 中。 You can do this in a loop, or recursively, or simply use reduce
:您可以在循环中或递归地执行此操作,或者简单地使用reduce
:
s1 = [0.89,0.43,0.28]
s2 = [0.89,0.43,0.99]
from functools import reduce # Python 3
reduce(lambda d, x: d[x], s1, dic)
reduce(lambda d, x: d[x], s2, dic)
Afterwards, dic
looks like this: (Actually, it looks a bit different, but that's only because of defaultdict
also printing the function it was created with.)之后, dic
看起来像这样:(实际上,它看起来有点不同,但这只是因为defaultdict
还打印了创建它的函数。)
{0.89: {0.43: {0.28: {}, 0.99: {}}}}
If by "the order of the sequences is important" you mean the order in which the sequences are added, and not the order within the sequences, you will have to use a collections.OrderedDict
instead.如果“序列的顺序很重要”是指添加序列的顺序,而不是序列中的顺序,则必须改用collections.OrderedDict
。 In this case, the adding of new elements is a bit more involved, but not by much.在这种情况下,添加新元素会更复杂一些,但不会太多。
dic = collections.OrderedDict()
def putall(d, s):
for x in s:
if x not in d:
d[x] = collections.OrderedDict()
d = d[x]
putall(dic, s1)
putall(dic, s2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.