導航:首頁 > 編程語言 > python樹

python樹

發布時間:2022-01-29 10:35:08

python中樹結構使用什麼實現的

這是數據結構的問題,按照數據結構中樹的實現即可,當然,要是圖方便也可以使用dict來模擬

② 用python中tkinter作圖怎麼畫樹的枝幹

class node: left=None right=None def __init__(self, parent=None): self.parent=parent 賦值的時候對應就好了。如root=node(),a=node(root),root.left=a,就有點像C語言里的指針了。

③ python如何獲取目錄樹

python獲取目錄樹需要用到os.walk函數,以下是一個例子。


importos

rootDir='d:\assa'
fordirName,subdirList,fileListinos.walk(rootDir):
print('Folder:%s'%dirName)
forfnameinfileList:
print(' %s'%fname)

來自:網頁鏈接

④ python怎麼動態畫出一棵樹

fromturtleimportTurtle

deftree(tList,length,angle,factor):
iflength>5:
lst=[]
fortintList:
t.forward(length);
temp=t.clone();
t.left(angle);
temp.right(angle);
lst.append(t);
lst.append(temp);
tree(lst,length*factor,angle,factor);

defmakeTree(x,y):
t=Turtle();
t.color('green');
t.pensize(5);
t.hideturtle();
#t.getscreen().tracer(30,0);
t.speed(10);
t.left(90);
t.penup();
t.goto(x,y);
t.pendown();
t=tree([t],110,65,0.6375);

makeTree(0,0)

⑤ 如何實現python控制樹

classnode:

def__init__(self,data):
self._data=data
self._children=[]

defgetdata(self):
returnself._data

defgetchildren(self):
returnself._children

defadd(self,node):
##iffull
iflen(self._children)==4:
returnFalse
else:
self._children.append(node)

defgo(self,data):
forchildinself._children:
ifchild.getdata()==data:
returnchild
returnNone

classtree:

def__init__(self):
self._head=node('header')

deflinktohead(self,node):
self._head.add(node)

definsert(self,path,data):
cur=self._head
forstepinpath:
ifcur.go(step)==None:
returnFalse
else:
cur=cur.go(step)
cur.add(node(data))
returnTrue

defsearch(self,path):
cur=self._head
forstepinpath:
ifcur.go(step)==None:
returnNone
else:
cur=cur.go(step)
returncur


'''
definenode
'''
a=node('A')
b=node('B')
c=node('C')
d=node('D')
e=node('E')
f=node('F')
g=node('G')
h=node('H')
i=node('I')
j=node('J')
k=node('K')
l=node('L')
m=node('M')
n=node('N')
o=node('O')

'''
addingnodetobuildtrue
'''
a.add(b)
a.add(g)
a.add(h)
b.add(c)
b.add(e)
g.add(i)
g.add(j)
g.add(k)
g.add(l)
h.add(m)
h.add(n)
h.add(o)
c.add(d)
c.add(f)
i.add(node(29))
j.add(node(28))
k.add(node(27))
l.add(node(26))
m.add(node(25))
n.add(node(24))
o.add(node(23))
f.add(node(30))


tree=tree()
tree.linktohead(a)


#testcase
print'Node',tree.search("ABE").getdata()
print'Node',tree.search("ABC").getdata()
print'Node',tree.search("AHM").getdata()
tree.insert("ABCD",1)
foriind.getchildren():
print'valueafter',d.getdata(),'is',i.getdata()

⑥ 求一個python的三叉樹演算法

這是網路上的一個版本,我自己做了一點修改,這是一個n叉樹,希望對你有所幫助

#!/usr/bin/python
#-*-coding:utf-8-*-
'''
Createdon2014-3-26

@author:qcq
'''

#==============================================================================
#tree.py:
#==============================================================================
#--
#$Revision:1.7$
#$Date:2000/03/2922:36:12$
#modifiedbyqcqin2014/3/27
#modifiedbyqcqin2014/4/23增加了遍歷樹的非遞歸版本的廣度優先和深度優先
#--

#================================================================
#Contents
#----------------------------------------------------------------
#classTree:Genericn-arytreenodeobject
#classNodeId:Representsthepathtoanodeinann-arytree
#----------------------------------------------------------------

#importstring


classTree:
"""Genericn-arytreenodeobject

Childrenareadditive;noprovisionfordeletingthem.
:0forthefirst
childadded,1forthesecond,andsoon.

modifiedbyqcqin2014/3/27.

Exports:
Tree(parent,value=None)Constructor
.parentIfthisistherootnode,None,otherwise
theparent'sTreeobject.
.childListListofchildren,zeroormoreTreeobjects.
.valueValuepassedtoconstructor;canbeanytype.
.birthOrderIfthisistherootnode,0,otherwisethe
indexofthischildintheparent's.childList
.nChildren()Returnsthenumberofself'schildren.
.nthChild(n)Returnsthenthchild;raisesIndexErrorif
nisnotavalidchildnumber.
.fullPath():.
.nodeId():ReturnspathtoselfasaNodeId.
"""


#---Tree.__init__---

def__init__(self,parent,value=None):
"""ConstructorforaTreeobject.

[if(parentisNoneoraTreeobject)->
if(parentisNone)->
,nochildren,
andvalue(value)
else->

ofparent(parent)andnochildren,andvalue(value)
]
"""
#--1--
self.parent=parent
self.value=value
self.childList=[]

#--2--
#-[if(parentisNone)->
#self.birthOrder:=0
#else->
#parent:=
#self.birthOrder:=sizeofparent's.childList
#-]
ifparentisNone:
self.birthOrder=0
else:
self.birthOrder=len(parent.childList)
parent.childList.append(self)


#---Tree.nChildren---

defnChildren(self):
"""[
]
"""
returnlen(self.childList)


#---Tree.nthChild---

defnthChild(self,n):
"""[if(nisaninteger)->
if(0<=n<(numberofself'schildren)->
returnself's(n)thchild,countingfrom0
else->
raiseIndexError
]
"""
returnself.childList[n]


#---Tree.fullPath---

deffullPath(self):
""".

[returnasequence[c0,c1,...,ci]suchthatselfis
root.nthChild(c0).nthChild(c1).....nthChild(ci),or
anemptylistifselfistheroot]
"""

#--1--
result=[]
parent=self.parent
kid=self

#--2--
#[result+:=childnumbersfromparenttoroot,in
#reverseorder]
whileparent:
result.insert(0,kid.birthOrder)
parent,kid=parent.parent,parent

#--3--
returnresult


#---Tree.nodeId---

defnodeId(self):
""".
"""
#--1--
#[fullPath:=sequence[c0,c1,...,ci]suchthatselfis
#root.nthChild(c0).nthChild(c1).....nthChild(ci),or
#anemptylistifselfistheroot]
fullPath=self.fullPath()

#--2--
returnNodeId(fullPath)

defequals(self,node):
'''
'''
returnself.value==node.value

#===========================================================================
#deletethenodefromthetree
#===========================================================================
defdelete(self):
ifself.parentisNone:
return
else:
#temp=self.birthOrder
'''
ifdeletethemiddletreeobject,
.
'''
self.parent.childList.remove(self.parent.childList[self.birthOrder])
fori,jinzip(range(self.birthOrder+1,self.parent.nChildren()),self.parent.childList[self.birthOrder+1:]):
j.birthOrder=j.birthOrder-1


defupdate(self,value):
'''

'''
self.value=value

def__str__(self):
return"The%dchildwithvalue%d"%(self.birthOrder,self.value)#-----classNodeId-----

classNodeId:
""".

Exports:
NodeId(path):
[->
-id]
.path:[aspassedtoconstructor]
.__str__():[returnselfasastring]
.find(root):
[ifrootisaTreeobject->

treerootedat(root)->
returnthe.valueofthatnode
else->
returnNone]
.isOnPath(node):
[ifnodeisaTreeobject->
->
return1
else->
return0]
"""

#---NodeId.__init__---

def__init__(self,path):
"""ConstructorfortheNodeIdobject
"""
self.path=path


#---NodeId.__str__---

def__str__(self):
"""Returnselfindisplayableform
"""

#--1--
#[L:=alistoftheelementsofself.pathconvertedtostrings]
L=map(str,self.path)

#--2--
#["/"]
returnstring.join(L,"/")


#---NodeId.find---

deffind(self,node):
"""
"""
returnself.__reFind(node,0)


#---NodeId.__reFind---

def__reFind(self,node,i):
"""Recursivenodefindingroutine.Startsatself.path[i:].

[if(nodeisaTreeobject)
and(0<=i<=len(self.path))->
ifi==len(self.path)->
returnnode'svalue
elseifself.path[i:]describesapathfromnode
tosometreeobjectT->
returnT
else->
returnNone]
"""

#--1--
ifi>=len(self.path):
returnnode.value#We'rethere!
else:
childNo=self.path[i]

#--2--
#[->
#child:=thatchildnode
#else->
#returnNone]
try:
child=node.nthChild(childNo)
exceptIndexError:
returnNone

#--3--
#[if(i+1)==len(self.path)->
#returnchild
#elseifself.path[i+1:]describesapathfromnodeto
#sometreeobjectT->
#returnT
#else->
#returnNone]
returnself.__reFind(child,i+1)


#---NodeId.isOnPath---

defisOnPath(self,node):
"""Isself'spathtoorthroughthegivennode?
"""

#--1--
#[nodePath:=pathlistfornode]
nodePath=node.fullPath()

#--2--
#[ifnodePathisaprefixof,oridenticaltoself.path->
#return1
#else->
#return0]
iflen(nodePath)>len(self.path):
return0#Nodeisdeeperthanself.path

foriinrange(len(nodePath)):
ifnodePath[i]!=self.path[i]:
return0#Nodeisadifferentroutethanself.path

return1

⑦ 用python畫一棵樹

1、准備

⑧ python裡面二項樹怎麼表示

class Tree:
def __init__(self,entry,left=None,right=None):
self.entry=entry
self.left=left
self.right=right
def __repr__(self):
args=repr(self.entry)
if self.left or self.right:
args+=',{0},{1}'.format(repr(self.left),repr(self.right))
return 'Tree({0})'.format(args)
def square_tree(t):
if t==None:
return
else:
t.entry=t.entry**2
square_tree(t.left)
square_tree(t.right)
def height(t):
if t==None:
return 0
else:
return 1+max(height(t.left),height(t.right))
def size(t):
if t==None:
return 0
else:
return size(t.left)+size(t.right)+1
def find_path(t,x):
if t==None:
return None
elif t.entry==x:
return (x,)
left=find_path(t.left,x);right=find_path(t.right,x)
if left:
return (t.entry,)+left
elif right:
return (t.entry,)+right
else:
return None
t=Tree(2,Tree(7,Tree(2),Tree(6,Tree(5),Tree(11))),Tree(15))
print(t)
a=find_path(t,5)
print(a)

⑨ python 怎樣實現多叉樹

class node:
def __init__(self, data):
self._data = data
self._children = []
def getdata(self):
return self._data
def getchildren(self):
return self._children
def add(self, node):
##if full
if len(self._children) == 4:
return False
else:
self._children.append(node)
def go(self, data):
for child in self._children:
if child.getdata() == data:
return child
return None
class tree:
def __init__(self):
self._head = node('header')
def linktohead(self, node):
self._head.add(node)
def insert(self, path, data):
cur = self._head
for step in path:
if cur.go(step) == None:
return False
else:
cur = cur.go(step)
cur.add(node(data))
return True
def search(self, path):
cur = self._head
for step in path:
if cur.go(step) == None:
return None
else:
cur = cur.go(step)
return cur

⑩ 如何實現Python多叉樹

classnode:

def__init__(self,data):
self._data=data
self._children=[]

defgetdata(self):
returnself._data

defgetchildren(self):
returnself._children

defadd(self,node):
##iffull
iflen(self._children)==4:
returnFalse
else:
self._children.append(node)

defgo(self,data):
forchildinself._children:
ifchild.getdata()==data:
returnchild
returnNone

classtree:

def__init__(self):
self._head=node('header')

deflinktohead(self,node):
self._head.add(node)

definsert(self,path,data):
cur=self._head
forstepinpath:
ifcur.go(step)==None:
returnFalse
else:
cur=cur.go(step)
cur.add(node(data))
returnTrue

defsearch(self,path):
cur=self._head
forstepinpath:
ifcur.go(step)==None:
returnNone
else:
cur=cur.go(step)
returncur


'''
definenode
'''
a=node('A')
b=node('B')
c=node('C')
d=node('D')
e=node('E')
f=node('F')
g=node('G')
h=node('H')
i=node('I')
j=node('J')
k=node('K')
l=node('L')
m=node('M')
n=node('N')
o=node('O')

'''
addingnodetobuildtrue
'''
a.add(b)
a.add(g)
a.add(h)
b.add(c)
b.add(e)
g.add(i)
g.add(j)
g.add(k)
g.add(l)
h.add(m)
h.add(n)
h.add(o)
c.add(d)
c.add(f)
i.add(node(29))
j.add(node(28))
k.add(node(27))
l.add(node(26))
m.add(node(25))
n.add(node(24))
o.add(node(23))
f.add(node(30))


tree=tree()
tree.linktohead(a)


#testcase
print'Node',tree.search("ABE").getdata()
print'Node',tree.search("ABC").getdata()
print'Node',tree.search("AHM").getdata()
tree.insert("ABCD",1)
foriind.getchildren():
print'valueafter',d.getdata(),'is',i.getdata()

閱讀全文

與python樹相關的資料

熱點內容
pythonswagger 瀏覽:231
作業打卡解壓素材 瀏覽:153
pdf導入ibooks 瀏覽:575
xps文件轉pdf 瀏覽:134
怎麼樣獲得命令方塊 瀏覽:899
安卓studio如何改主題 瀏覽:933
linux自動獲取ip命令行 瀏覽:208
做設計做程序員適合的電腦 瀏覽:778
網站有源碼和沒有源碼的區別 瀏覽:680
如何自學開發app 瀏覽:595
修電梯pdf 瀏覽:351
政務雲是不是提供虛擬伺服器 瀏覽:59
在哪裡看每個app用了多長時間 瀏覽:637
學程序員要英語四級嗎 瀏覽:133
java視頻錄制 瀏覽:758
口頭指派式命令 瀏覽:474
php開發工程師面試題 瀏覽:954
linux內核源碼pdf 瀏覽:66
mc命令方塊怎麼提取 瀏覽:367
有關程序員的五大魔咒你中了幾個 瀏覽:204