[python]CategoryTree的设计与实现
2016-05-03 16:42
573 查看
CatagoryTree的设计与实现
题目要求
今天的面试题是20min用python实现目录树:#输入 if __name__== '__main__': c = CatagoryTree() c.add_catagory('A',None) c.add_catagory('B','A') c.add_catagory('C','A') print ','.join(c .get_children('A'))
输出:B,C或者C,B
设计
+--------------+ | object | +--------------+ . /_\ | [ object ] | . | /_\ | | | | +--------------+ +----------+ | CatagoryTree | | Node | |--------------| |----------| | tree | | base | |--------------| | parent | | __init__ | | children | | add_catagory | |----------| | get_children | | __init__ | +--------------+ +----------+
实现
#-*- coding:utf-8 -*- class CatagoryTree(object): def __init__(self): self.tree = [] class Node(object): def __init__(self,base,parent=(None),children=[]):#parent只能有一个,应该是Tuple类型。而children长度是可变的,应该是List类型 self.base= base self.parent = parent self.children = children def add_catagory(self,a,b): #当b为None时,将a作为tree的根节点 if b is None: a = self.Node(a) self.tree.append(a) else: #不然的话,就遍历tree flag = False for _ in self.tree: #当找到b时,将a插入b的孩子节点中 if _.base ==b: a = self.Node(a) _.children.append(a) a.parent = _.base flag = True #当找不到b时,抛异常 if not flag: print 'Parent Node %s is not exist!'%a def get_children(self,a): #遍历tree找a #if 找到: #return a.children #else: #return 'a is not exist.' it = iter(self.tree) while(True): try: _ = next(it) if _.base==a: return [__.base for __ in _.children] except StopIteration: print 'Base Node %s !exist'%a break if __name__== '__main__': c = CatagoryTree() c.add_catagory('A',None) c.add_catagory('B','A') c.add_catagory('C','A') print ','.join(c .get_children('A')) c.get_children('D') c.add_catagory('C','D')
相关文章推荐
- python常用代码
- Python入门
- 在Vim中执行Python
- python中os.walk浏览目录和文件
- 『Python高级编程』学习笔记之二: 第十章——编写项目文档
- Python3爬虫入门之贴吧图片批量获取
- 批量更名
- python的魔术方法
- python成功配置scikit-learn,含试错历程
- Python file.seek()文件游标移动操作方法
- 使用python抓取豆瓣电影信息
- Python Rate Limiter
- python读conf配置文件--ConfigParser
- Python基础
- python list列表排序的两种方法及实例讲解
- Python实现欧拉计划20题
- Python OS 文件/目录方法
- python and or 的高级用法
- Python的yield协程机制实现生产者-消费者模式
- Python中super关键字的作用