2017-05-24 9 views
0

以下のヒープショーを表すリストがあります。親の左右の子をヒープから印刷します。

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

私は入力に親の位置をユーザーに尋ねる関数を記述すると、親が持っていない場合、この関数は親、左の子と右の子またはfalseの値を出力します必要子供。

次のコードを試してみましたが、エラーが表示されます。ユーザーが位置入力として0を入力すると

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) 

出力例は次のようになります。

Parent: 8 
Left child: 4 
Right child: 7 
+0

あなたは '右の子をプリントアウトすることができる方法:7'あなたのスクリプト内の任意の場所にコードを書いていない間?第2に、 'i'が7に等しい' children'関数では、 'L [15]'に項目がないので 'list index of range'エラーを返します。あなたの 'L''リストには5つの項目しか含まれていないので、最大のインデックスは4です。 – arnold

+0

私は目標が完全にわかりません - 親が8の場合は、左の子供は4歳ですか?何かあればそれは1でなければなりませんか? –

+0

ここでループはなぜ必要ですか?あなたはコード内で正しい子をどこに印刷していますか? – Pavan

答えて

0

あなたは真実文にこのような関数を使用してループを回避することができます。

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(): 
... 
0

コードは次のようになります。

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 
関連する問題