设为首页 加入收藏

TOP

Python: tree data structure(一)
2017-10-09 16:54:54 】 浏览:1008
Tags:Python: tree data structure
# 树结构
from pythonds.basic.stack import Stack  #pip install pythonds
from pythonds.trees.binaryTree import BinaryTree 
from collections import defaultdict
import json

#JSON-esque
def tree(): 
    return defaultdict(tree)

def dicts(t): 
    return {k: dicts(t[k]) for k in t}

#迭代
def add(t, keys):   
    for key in keys:     t = t[key]

users = tree();
users['harold']['username'] = 'hrldcpr' 
users['handler']['username'] = 'matthandlersux';

print(json.dumps(users));

taxonomy = tree(); 
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat'] 
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion'] 
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog'] 
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote'] 
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato'] 
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato'] 
taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']

print(dicts(taxonomy));

dtstr=add(taxonomy,'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))





def buildParseTree(fpexp):
  fplist = fpexp.split()
  pStack = Stack()
  eTree = BinaryTree('')
  pStack.push(eTree)
  currentTree = eTree
  for i in fplist:
    if i == '(':
      currentTree.insertLeft('')
      pStack.push(currentTree)
      currentTree = currentTree.getLeftChild()
    elif i not in ['+', '-', '*', '/', ')']:
      currentTree.setRootVal(int(i))
      parent = pStack.pop()
      currentTree = parent
    elif i in ['+', '-', '*', '/']:
      currentTree.setRootVal(i)
      currentTree.insertRight('')
      pStack.push(currentTree)
      currentTree = currentTree.getRightChild()
    elif i == ')':
      currentTree = pStack.pop()
    else:
      raise ValueError
  return eTree

pt = buildParseTree("( ( 10 + 5 ) * 3 )")
pp= pt.postorder() #defined and explained in the next section

 

 

输出结果:

{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Felidae': {'Panthera': {'lion': {}}, 'Felis': {'cat': {}}}, 'Canidae': {'Canis': {'dog': {}, 'coyote': {}}}}}}}, 'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}}, 'Solanaceae': {'Solanum': {'tomato': {}, 'potato': {}}}}}}
10
5
+
3
*
('In', 'the')
('the', 'beginning')
('beginning', 'god')
('god', 'created')
('created', 'the')
('the', 'heaven')
('heaven', 'and')
('and', 'the')
('the', 'earth')
('earth', '.')
涂聚文,geovindu
geovindu-PC
192.168.20.210
hello word 你好,世界
win32
1267650600228229401496703205376
输入的内容:

 

 2.

import uuid;

#Python3.5

class TreeNode(object):
    def __init__(self, data = -1, lchild = None, rchild = None):
        self.data = data
        self.lchild = lchild
        self.rchild = rchild

class BinaryTree(object):
    def __init__(self):
        self.root = TreeNode()

    def add(self, data):
        node = TreeNode(data)
        if self.isEmpty():
            self.root = node
        else:
            tree_node = self.root
            queue = []
            queue.append(self.root)

            while queue:
                tree_node = queue.pop(0)
                if tree_node.lchild == None:
                    tree_node
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python学习笔记第一周 下一篇copytest.py

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目