导航:首页 > 编程语言 > 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树相关的资料

热点内容
php备案号 浏览:986
php视频水印 浏览:163
怎么追程序员的女生 浏览:485
空调外压缩机电容 浏览:77
怎么将安卓变成win 浏览:457
手机文件管理在哪儿新建文件夹 浏览:724
加密ts视频怎么合并 浏览:775
php如何写app接口 浏览:804
宇宙的琴弦pdf 浏览:396
js项目提成计算器程序员 浏览:944
pdf光子 浏览:834
自拍软件文件夹名称大全 浏览:328
程序员留学移民 浏览:52
梁中间部位箍筋加密区 浏览:119
频谱分析pdf 浏览:752
乐2怎么升级安卓70 浏览:174
java中获取日期 浏览:508
单片机74hc245 浏览:274
美国历史上的总统pdf 浏览:753
程序员脱单实验室靠不靠谱 浏览:460