蟒蛇最低的共同祖先 [英] python lowest common ancestor
问题描述
什么是在Python实现最低的共同祖先的最简单的方法?我有重新由具有指向其父每个节点psented $ P $一棵树,我希望能够找到给两个节点的共同祖先。我已经想出了一些想法,但没有一个是特别有吸引力
-
让每个节点包含其基地名单,并进行联接,找到最长的共同preFIX然后取最后一个元素。不幸的是,我不知道任何内置的方式做到最长的公共preFIX所以这需要手动循环。
-
让每个节点包含了一组其基地和执行交集,并采取最大元素。但是,这需要定义自定义比较运算,我甚至不知道是否会工作。
我应该怎么办?我在找的东西,有利于简便了性能,因此需要复杂的处理解决方案都出来了。
编辑:我发现,虽然没有一个内置的方式,你可以用拉链做最长的共同preFIX在一行中,所以它仍然是相当简单
。 普通= [X对于x的ZIP(* baselists)如果len(集(X))== 1] [ - 1]
根据的假设,你不能修改你的树,包括深度,你可以做到以下几点:
对于每个节点,递归遍历树向上,直到你打根。在每个父节点,接入节点到列表
。这应该给你 list_a
和 list_b
。遍历最短的列表,比较从每个列表元素。当你发现一个不匹配,previous项即是最大的父元素。
What is the easiest way to implement lowest common ancestor in Python? I have a tree which is represented by each node having a pointer to its parent, and I want to be able to find the first common ancestor given two nodes. I've come up with several ideas but none are particularly appealing
Have each node contain a list of its bases, and to perform a join, find the longest common prefix and then take the last element. Unfortunately, I don't know of any builtin way to do longest common prefix so this requires manual looping.
Have each node contain a set of its bases and perform a set intersection, and take the maximum element. But this requires defining custom comparison operators, and I'm not even sure if it would work.
What should I do? I'm looking for something that favors simplicity over performance, so solutions requiring complicated processing are out.
Edit: I discovered that while there isn't a builtin way, you can do longest common prefix in one line using zip, so it's still fairly simple.
common = [x for x in zip(*baselists) if len(set(x)) == 1][-1]
Under the assumption that you cannot amend your tree to include depth, you can do the following:
For each Node, recursively traverse the tree upwards until you hit the root. At each parent node, insert the node into a list
. This should give you list_a
and list_b
. Iterate over the shortest list, comparing elements from each list. When you find one that doesn't match, the previous entry is your largest parent element.
这篇关于蟒蛇最低的共同祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!