鉴于以下代码,我只有一个问题。我尝试打印“ Noeud”类实例的元素列表(list_fils),但是它给了我这个(节点0的示例):
Children of Node 0 are: [<__main__.Noeud object at 0x7f7d1a5009b0>, <__main__.Noeud object at 0x7f7d1a500b38>]
我该怎么做才能打印列表中的元素?这是我的程序:
class Noeud:
def __init__(self,val):
self.val=val
self.list_fils=[] #list containing children of the instance
# K is number of levels of our binary tree
#if we have k=2 levels, we need to iterate until Node with index (2^0)-1=0
#if we have k=3 levels, we need to iterate until Node with index (2^0 + 2^1)-1 = 2
#if we have k=4 levels, we need to iterate until Node with index (2^0 + 2^1 + 2^2)-1=6
#if we have k levels, we need to iterate until Node with index (2^0+ 2^1 +.....+2^(k-2))
def stop_index_for_level(K):
Sum=0
for x in range(K-1):
Sum+=2**x
return Sum-1
#for each node(i) in l we add children of this node(i) to the list_fils attribute
def Exo3(K,l):
Debut=1
for i in range(stop_index_for_level(K)+1):
Fin=Debut+2
l[i].list_fils.extend(l[Debut:Fin])
Debut=Fin
#our binary tree example (Note: each level must be completed)
#0
#/ \
#1 2
#/\ /\
#3 4 5 6
List_Nodes=[Noeud(i) for i in range(7)] #[0,1,2,3,4,5,6]
Exo3(3,List_Nodes)
for x in range(len(List_Nodes)):
print("Children of Node ",List_Nodes[x].val," are: ",List_Nodes[x].list_fils)