【问题标题】:Printing the left and right child of a parent from a heap.从堆中打印父母的左右孩子。
【发布时间】:2017-05-24 02:49:33
【问题描述】:

我有一个代表下面堆显示的列表。

L = [8,4,7,2,3,1] 

我需要编写一个函数,要求用户输入父母的位置,然后该函数将打印父母、左孩子和右孩子的值,如果父母没有孩子,则为 false。

我尝试了以下代码,但我得到了一个错误。

position = int(input("Enter the position: "))

L = [8,7,2,3,1]

print("Parent:",heapList[position])

def children(L, position):
    for i in L:
        if L[2*i+1] not in L:
            return False
        else:
            print("Left Child",L[2*i+1])

children(L, position)

当用户输入 0 作为位置输入时,输出示例应如下所示:

Parent: 8
Left child: 4
Right child: 7

【问题讨论】:

  • 当您不在脚本中的任何位置编写代码时,如何打印出Right child: 7?其次,在你的children函数中,例如i等于7,那么它会返回list index out of range错误,因为L[15]中没有项目。您的L list 仅包含 5 个项目,这意味着 index 最多为 4 个。
  • 我不确定我是否完全实现了目标 - 如果父母是 8 岁,那么我知道右孩子是 7 岁,但为什么左孩子会是 4 岁?如果有的话,它应该是 1 对吗?
  • 嗨,为什么这里需要循环?你在代码中的哪里打印正确的孩子?

标签: python


【解决方案1】:

你可以通过使用这些函数来避免循环。

def has_childern(self):
    return self.right_child or self.left_child

def has_both_childern(self):
    return self.right_child and self.left_child

然后只使用嵌套的 if,作为示例。

if current_node.has_both_childern():
...
elif current_node.has_left_child():
...

【讨论】:

    【解决方案2】:

    代码应如下所示:

    L_heap = [8,4,7,2,3,1]
    def children(L, position):
        if position > len(L) - 1 :
           print("There is no node at this heap position", position)
           return
        else:
           print("Parent", L[position]
        if (2*position+1) > len(L)-1:
            print("No childs")
            return
        else:
            print("Left Child",L[2*position+1])
            if not((2*position+2) > len(L)-1):
               print("Right Child",L[2*position +2])
        return
    
    children(L_heap, 0)
    children(L_heap, 5)
    children(L_heap, 3)
    children(L_heap, 8)
    

    输出:

    Parent 8
    Left Child 4
    Right Child 7
    Parent 1
    No childs
    Parent 2
    No childs
    There is no node at this heap position 8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      相关资源
      最近更新 更多