Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BFS查找和排序二叉树中的近亲_Python_Sorting_Binary Tree_Breadth First Search - Fatal编程技术网

Python 使用BFS查找和排序二叉树中的近亲

Python 使用BFS查找和排序二叉树中的近亲,python,sorting,binary-tree,breadth-first-search,Python,Sorting,Binary Tree,Breadth First Search,我试图在二叉树中识别特定家庭成员的所有堂兄弟姐妹的名字。 输入数据是以下格式的列表列表: family = [ ['George', 75, ['Bob', 'Vicky']], ['Bob', 48, ['Tom', 'Sophie']], ['Vicky', 42, ['Karen']], ['Tom', 23, []], ['Sophie', 21, []], ['Karen', 19, []] ] 其中,每个列表表示[个人、年龄、[child1、child2]] 每个人最多可以

我试图在二叉树中识别特定家庭成员的所有堂兄弟姐妹的名字。 输入数据是以下格式的列表列表:

family = 
[
['George', 75, ['Bob', 'Vicky']],
['Bob', 48, ['Tom', 'Sophie']],
['Vicky', 42, ['Karen']], 
['Tom', 23, []], 
['Sophie', 21, []], 
['Karen', 19, []]
]
其中,每个列表表示
[个人、年龄、[child1、child2]]
每个人最多可以有两个孩子。父母的信息总是在孩子的信息之前给出,没有两个名字是相同的。表兄弟姐妹们应该是最年轻的。表兄弟姐妹同龄时,应按字母顺序排列

示例函数和输出:

>>> cousins("Tom", family)

>>> ['Karen']
>>表亲(个人、家庭)

>>['cousin1','cousin2',…]

我迄今为止的努力:

import math
import operator

def BFS(tree,level=["brown"]):
    """breadth-first search on tree."""
    bfs_list = []
    if len(level) > 0:
        bfs_list += level
        sub_level = []
        for vertex in level:
            if vertex not in tree:
                continue
            sub_level += tree[vertex]
        bfs_list += BFS(tree,sub_level)
    return bfs_list

def siblings(g,h,lst):
    """determine if two nodes are sibling."""
    return any([(g in lst[k]) and (h in lst[k]) for k in lst])

def parent_child(a,b,lst):
    """determine if two nodes have a parent-child relationship."""
    return any([(a in lst[b]), (b in lst[a])])

def cousins(p, people):
    """determine cousins of a family member."""
    famdict = {lst[0]:lst[2] for lst in people}
    agelst = sorted([(j[0], j[1]) for j in people], key=operator.itemgetter(1, 0))
    names = BFS(famdict, [people[0][0]])
    i = names.index(p)+1
    s = math.floor(math.log2(i))
    e = 1 + s
    pcuz = names[2**s-1:(2**e)-1]
    f = [n for n in pcuz if all([(not parent_child(p,n,famdict)), (not siblings(p,n,famdict))])]
    return [q[0] for q in agelst if q[0] in f]
输入和输出示例:

>>> cousins("Tom", family)

>>> ['Karen']

到目前为止,我的实现似乎工作正常,但由于运行时错误,有时会超时。如何解决此问题?

一种可能是找到家庭成员到目标成员的路径,然后备份返回的结果:

family = [['George', 75, ['Bob', 'Vicky']], ['Bob', 48, ['Tom', 'Sophie']], ['Vicky', 42, ['Karen']], ['Tom', 23, []], ['Sophie', 21, []], ['Karen', 19, []]]
def paths(d, s, t, c = []):
   if s == t:
      yield c
   else:
      for i in d[s]['children']:
        yield from paths(d, i, t, c+[s])

def cousins(person, family):
  f = {a:{'age':b, 'children':c} for a, b, c in family}
  r = max([i for a in f for i in paths(f, a, person)], key=len)
  if len(r) < 2:
     return []
  *_, g, p = r
  return sorted([i for b in f[g]['children'] for i in f[b]['children'] if b != p], key=lambda x:(f[x]['age'], x))


print(cousins('Tom', family))
print(cousins('Bob', family))

一种可能是找到家庭成员到目标成员的路径,然后备份返回的结果:

family = [['George', 75, ['Bob', 'Vicky']], ['Bob', 48, ['Tom', 'Sophie']], ['Vicky', 42, ['Karen']], ['Tom', 23, []], ['Sophie', 21, []], ['Karen', 19, []]]
def paths(d, s, t, c = []):
   if s == t:
      yield c
   else:
      for i in d[s]['children']:
        yield from paths(d, i, t, c+[s])

def cousins(person, family):
  f = {a:{'age':b, 'children':c} for a, b, c in family}
  r = max([i for a in f for i in paths(f, a, person)], key=len)
  if len(r) < 2:
     return []
  *_, g, p = r
  return sorted([i for b in f[g]['children'] for i in f[b]['children'] if b != p], key=lambda x:(f[x]['age'], x))


print(cousins('Tom', family))
print(cousins('Bob', family))

我修改了这棵树,使“约翰”和“凯特”是表亲

family = [
["brown", 88, ["chad", "stacy"]],
["chad", 50, ["kirk", "margon"]], 
["stacy", 48, ["simone","sam"]], 
["simone", 18, ["kate"]], 
["kirk", 25, ["john"]], 
["margon", 20, []], 
["john", 10,[]],
["kate",4,[]], 
["sam",3,[]]
]

def paths(d, s, t, c = []):
   if s == t:
      yield c
   else:
      for i in d[s]['children']:
        yield from paths(d, i, t, c+[s])

def cousins(person, family):
  f = {a:{'age':b, 'children':c} for a, b, c in family}
  r = max([i for a in f for i in paths(f, a, person)], key=len)
  if len(r) < 2:
     return []
  *_, g, p = r
  return sorted([i for b in f[g]['children'] for i in f[b]['children'] if b != p], key=lambda x:(f[x]['age'], x))


print(cousins('kate', family))
系列=[
[“布朗”、88、[“查德”、“斯泰西”],
[“chad”,50,[“kirk”,“margon”],
[“stacy”,48,[“simone”,“sam”],
[“西蒙妮”,18,[“凯特”],
[“柯克”,25,[“约翰”],
[“margon”,20,[],
[“约翰”,10,[],
[“凯特”,4,[],
[“山姆”,3,[]
]
定义路径(d、s、t、c=[]):
如果s==t:
产量c
其他:
因为我在d[s][“孩子们”]:
路径(d、i、t、c+[s]的产量)
def表亲(个人、家庭):
f={a:{‘年龄’:b,‘子女’:c}表示家庭中的a、b、c}
r=最大值([i代表路径中的a,f代表路径中的i(f,a,person)],key=len)
如果len(r)<2:
返回[]
*_,g,p=r
返回排序([i代表f[g]中的b]['children']代表f[b]['children']中的i,如果b!=p],key=lambda x:[f[x]['age'],x))
印刷品(表亲(凯特家族))

但是,此代码返回[]。

我修改了树,使“john”和“kate”是表亲

family = [
["brown", 88, ["chad", "stacy"]],
["chad", 50, ["kirk", "margon"]], 
["stacy", 48, ["simone","sam"]], 
["simone", 18, ["kate"]], 
["kirk", 25, ["john"]], 
["margon", 20, []], 
["john", 10,[]],
["kate",4,[]], 
["sam",3,[]]
]

def paths(d, s, t, c = []):
   if s == t:
      yield c
   else:
      for i in d[s]['children']:
        yield from paths(d, i, t, c+[s])

def cousins(person, family):
  f = {a:{'age':b, 'children':c} for a, b, c in family}
  r = max([i for a in f for i in paths(f, a, person)], key=len)
  if len(r) < 2:
     return []
  *_, g, p = r
  return sorted([i for b in f[g]['children'] for i in f[b]['children'] if b != p], key=lambda x:(f[x]['age'], x))


print(cousins('kate', family))
系列=[
[“布朗”、88、[“查德”、“斯泰西”],
[“chad”,50,[“kirk”,“margon”],
[“stacy”,48,[“simone”,“sam”],
[“西蒙妮”,18,[“凯特”],
[“柯克”,25,[“约翰”],
[“margon”,20,[],
[“约翰”,10,[],
[“凯特”,4,[],
[“山姆”,3,[]
]
定义路径(d、s、t、c=[]):
如果s==t:
产量c
其他:
因为我在d[s][“孩子们”]:
路径(d、i、t、c+[s]的产量)
def表亲(个人、家庭):
f={a:{‘年龄’:b,‘子女’:c}表示家庭中的a、b、c}
r=最大值([i代表路径中的a,f代表路径中的i(f,a,person)],key=len)
如果len(r)<2:
返回[]
*_,g,p=r
返回排序([i代表f[g]中的b]['children']代表f[b]['children']中的i,如果b!=p],key=lambda x:[f[x]['age'],x))
印刷品(表亲(凯特家族))

但是,此代码返回[]。

我尝试了您的代码,但每当我输入一个没有任何表亲的人(“Bob”)时,我都会得到一个ValueError。我想一个空的名单,以返回时,一个人没有表亲。你能修改你的代码来包含它吗。谢谢。@Clifton谢谢你的评论,请看我最近的编辑。它似乎适用于这里给出的树。这是这类树的通用算法吗?@Clifton是的,我写这个算法是为了处理
[name,age,[children]]
格式的树。但是,请告诉我是否有更具体的输入案例需要处理。它给了我预期的测试结果,但在HackerRank中,它只通过了一个测试案例,并告诉我答案是错误的。我不确定这里出了什么问题。我尝试了你的代码,但每当我输入一个没有任何表亲的人(“Bob”)时,我就会得到一个ValueError。我想一个空的名单,以返回时,一个人没有表亲。你能修改你的代码来包含它吗。谢谢。@Clifton谢谢你的评论,请看我最近的编辑。它似乎适用于这里给出的树。这是这类树的通用算法吗?@Clifton是的,我写这个算法是为了处理
[name,age,[children]]
格式的树。但是,请告诉我是否有更具体的输入案例需要处理。它给了我预期的测试结果,但在HackerRank中,它只通过了一个测试案例,并告诉我答案是错误的。我不确定这里有什么问题。
[]
确实应该是该示例的正确输出,因为凯特的祖先是
['brown','stacy','simone']
。因此,从史黛西开始,凯特的叔叔是“山姆”,然而,
“山姆”
指向一个空列表(
sam
没有孩子)。因此,凯特没有表亲。
[]
确实应该是该示例的正确输出,因为凯特的祖先是
['brown','stacy','simone']
。因此,从史黛西开始,凯特的叔叔是“山姆”,然而,
“山姆”
指向一个空列表(
sam
没有孩子)。因此,凯特没有表亲。