[python]CategoryTree的设计与实现

65 篇文章 16 订阅
4 篇文章 0 订阅

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')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值