python中任意数

xiaoxiao2021-02-28  103

学校             商学院     法学院    电子学院       计算机学院                                                        软件        网络       数据                                                                  网1 网2 网3 1.根据当前节点 获取父节点 2.根据当前节点 获取所有子节点 3.根据当前节点 获取所有祖先节点 4.根据当前节点 获取所有子孙节点 5.根据当前节点 获取所有兄弟节点 class Tree:     childToParent=None     parentToChildren=None     def add(self,parent,child):         if self.childToParent  is None:  #如果childToParent 是空的话:             self.childToParent={child:parent} #转集合         else:             self.childToParent[child]=parent         if self.parentToChildren is None:             self.parentToChildren={parent:[]} #父亲对应 多个孩子         children=self.parentToChildren.get(parent,[])         if len(children)==0:             self.parentToChildren[parent]=children         children.append(child) #直接追加     def getParent(self,child):         return self.childToParent.get(child,'没有父亲的节点')     def getChildren(self,parent):         return self.parentToChildren.get(parent,'没下级')     def getZuXian(self,zisun):         '''         思想就是 递归问爹        1.可以获取上一级 getParent        2.如果我能够让上一级返回的数据在 执行 getParent 依次执行 直到没有上级终止         :param zisun:         :return:         '''         parent = self.getParent(zisun)         if parent is None:             return []         zupu= self.getZuXian(parent)         zupu.append(parent)         return zupu     #第四     def zisun(self,zs,zu):         '''         1.得到当前节点的孩子        2.遍历当前节点的孩子 每一个孩子去得到他们的孩子         :param zs: 结果         :param zu: 条件         :return:         '''         children=self.getChildren(zu)         if children == '没下级':             return         for c in children:             self.zisun(zs,c)         zs.extend(children)         #第5     def getSibling(self,sibling):         parent=self.getParent(sibling)         children=self.getChildren(parent)         children.remove(sibling)         return  children if __name__=='__main__':     tree=Tree()     tree.add(None,'学校')     tree.add('学校','商学院 ')     tree.add('学校','法学院')     tree.add('学校','电子学院 ')     tree.add('学校','计算机学院')     tree.add('计算机学院','软件')     tree.add('计算机学院','网络')     tree.add('计算机学院','数据')     tree.add('网络','网1')     tree.add('网络','网2')     tree.add('网络','网3') #1.根据当前节点获取父节点  网路     child='网络'     parent=tree.getParent(child)     print('{1}的上级是:{0}'.format(parent,child)) #2. 根据当前节点 获取所有子节点     parent = '计算机学院'     children = tree.getChildren(parent)     print('{0}的子级是:{1}'.format(parent,children)) # 3.根据当前节点 获取所有祖先节点 ancestor     zisun = '网3'     zuxian=tree.getZuXian(zisun)     print('{0}的祖先是:{1}'.format(zisun, zuxian)) #4. 根据当前节点 获取所有子孙节点     zu='学校'     zs=[]     tree.zisun(zs,zu)     print('{0}的子孙是:{1}'.format(zu,zs)) #5. 根据当前节点 获取所有兄弟节点     sibling='法学院'     rs = tree.getSibling(sibling)     print('{0}的兄弟是:{1}'.format(sibling,rs)) 运行结果如图:

完毕!
转载请注明原文地址: https://www.6miu.com/read-2632345.html

最新回复(0)