Python 용 BeautifulSoup 라이브러리에는 노드 목록을 취하여 가장 낮은 공통 조상을 반환 할 수있는 함수가 있습니까?BeautifulSoup 가장 낮은 공통 조상
그렇다면이 기능을 구현하고 공유하는 사람이 있습니까?
Python 용 BeautifulSoup 라이브러리에는 노드 목록을 취하여 가장 낮은 공통 조상을 반환 할 수있는 함수가 있습니까?BeautifulSoup 가장 낮은 공통 조상
그렇다면이 기능을 구현하고 공유하는 사람이 있습니까?
저는 이것이 여러분이 원하는 것이라고 생각합니다. link1은 하나의 요소이고 link2는 다른 것입니다.
link_1_parents = list(link1.parents)[::-1]
link_2_parents = list(link2.parents)[::-1]
common_parent = [x for x,y in zip(link_1_parents, link_2_parents) if x is y][-1]
print common_parent
print common_parent.name
그것은 기본적으로 아래로 루트에서 두 요소의 부모를 걸어, 마지막 일반적인 하나를 반환 할 수 있습니다.
입력 목록의 태그에서 최소 공통 조상까지의 거리가 입력의 모든 노드에 대해 정확하지 않은 경우 허용되는 대답이 작동하지 않습니다.
또한 각 노드의 모든 조상을 사용하므로 불필요하고 경우에 따라 매우 비쌀 수 있습니다.
import collections
def lowest_common_ancestor(parents=None, *args):
if parents is None:
parents = collections.defaultdict(int)
for tag in args:
if not tag:
continue
parents[tag] += 1
if parents[tag] == len(args):
return tag
return lowest_common_ancestor(parents, *[tag.parent if tag else None for tag in args])
선형 트리 a-b-c-d-e-f-g의 경우 알고리즘이 작동하지 않는 것으로 보입니다. LCA (b, g)는 b 여야하지만 알고리즘 a를 돌려 준다. –
고마워요! 너는 완벽하게 맞았다. 나는 그 코드를 올바르게 처리하기 위해 코드를 수정했습니다. – Arthur
코드의 의미는 아닙니다. Chang의 대답은 I Chang의 코멘트입니다. 우리가 * 모든 * 태그를 트리에서 한 레벨 위로 이동했기 때문에'* [tag.parent if else else for args]'를 할 때 문제가 발생합니다. 나는 Joachim Isaksson에서 영감을 얻은 접근법을 사용했습니다. – Octavius
경우에 따라 아서의 대답이 올바르지 않습니다. 아서의 대답을 수정하고 내 대답을 알려줍니다. 두 노드를 입력으로하여 LCA 코드를 테스트했습니다.
import collections
def lowest_common_ancestor(parents=None, *args):
if parents is None:
parents = collections.defaultdict(int)
for tag in args:
parents[tag] += 1
if parents[tag] == NUM_OF_NODES:
return tag
next_arg_list = [tag.parent for tag in args if tag.parent is not None]
return lowest_common_ancestor(parents, *next_arg_list)
전화 기능과 같은 :
list_of_tag = [tag_a, tag_b]
NUM_OF_NODES = len(list_of_tag)
lca = lowest_common_ancestor(None, *list_of_tag)
print(lca)
그렇진. 링크가 두 개가 아니라 다양한 수의 링크에서 작동 할 수 있기를 원하지만 직접 편집 할 수 있습니다. 고맙습니다. –
@Arthur가 지적했듯이, 2 개의 노드가 같은 깊이에있을 때만 작동합니다. – Laurie