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.lchild = node
- return
- elif tree_node.rchild == None:
- tree_node.rchild = node
- return
- else:
- queue.append(tree_node.lchild)
- queue.append(tree_node.rchild)
- def pre_order(self, start):
- node = start
- if node == None:
- return
- print(node.data),
- if node.lchild == None and node.rchild == None:
- return
- self.pre_order(node.lchild)
- self.pre_order(node.rchild)
- def pre_order_loop(self):
- if self.isEmpty():
- return
- stack = []
- node = self.root
- while node or stack:
- while node:
- print(node.data),
- stack.append(node)
- node = node.lchild
- if stack:
- node = stack.pop()
- node = node.rchild
- def in_order(self, start):
- node = start
- if node == None:
- return
- self.in_order(node.lchild)
- print(node.data),
- self.in_order(node.rchild)
- def in_order_loop(self):
- if self.isEmpty():
- return
- stack = []
- node = self.root
- while node or stack:
- while node:
- stack.append(node)
- node = node.lchild
- if stack:
- node = stack.pop()
- print(node.data),
- node = node.rchild
- def post_order(self, start):
- node = start
- if node == None:
- return
- self.post_order(node.lchild)
- self.post_order(node.rchild)
- print(node.data),
- def post_order_loop(self):
- if self.isEmpty():
- return
- node = self.root
- stack = []
- queue = []
- queue.append(node)
- while queue:
- node = queue.pop()
- if node.lchild:
- queue.append(node.lchild)
- if node.rchild:
- queue.append(node.rchild)
- stack.append(node)
- while stack:
- print(stack.pop().data),
- #if lchild and rchild are None or lchild and rchild are printed, print the parent node node and pop out of the stack
- #else lchild and rchild push into the stack
- def post_order_loop1(self):
- if self.isEmpty():
- return
- stack = []
- top = -1
- node = self.root
- stack.append(node)
- #we need to recognize the last printed node
- top += 1
- pre = None
- while stack:
- node = stack[-1]
- if node.lchild is None and node.rchild is None:
- print(node.data),
- pre = node
- top -= 1
- elif not pre and (node.lchild == pre or node.rchild == pre):
- print(node.data),
- pre = node
- top -= 1
- else:
- if node.rchild:
- if top < len(stack)-1:
- stack[top] = node.rchild
- else:
- stack.append(node.rchild)
- if node.lchild:
- if top < len(stack)-1:
- stack[top] = node.lchild
- else:
- stack.append(node.lchild)
- def level_order(self):
- node = self.root
- if node == None:
- return
- queue = []
- queue.append(node)
- while queue:
- node = queue.pop(0)
- print(node.data),
- if node.rchild:
- queue.append(node.rchild)
- if node.lchild:
- queue.append(node.lchild)
- def isEmpty(self):
- return True if self.root.data == -1 else False
- class NodeTu:
- def __init__(self, value, next=None):
- self.value = value;
- self.next = next;
- class NodeDu:
- def __init__(self, value, left=None, right=None):
- self.value = value
- self.left = left
- self.right = right
测试:
- import nltk;
- import pandas;
- import matplotlib;
- import math;
- import os;
- import unittest;
- #from nltk.parse.featurechart import trees
- import NodeDu;
- import copy;
- import NodeTu;
- import TreeNode;
- from nltk.tree import ParentedTree;
- #Python 3.5
- #from platform import node
- #1. tree data structure
- arr = []
- for i in range(10):
- arr.append(i)
- print(arr);
- tree =TreeNode.BinaryTree();
- for i in arr:
- tree.add(i)
- print('level_order:');
- tree.level_order();
- print('pre order:');
- tree.pre_order(tree.root)
- print('\npre order loop:');
- tree.pre_order_loop()
- print('\nin_order:');
- tree.in_order(tree.root)
- print('\nin_order loop:');
- tree.in_order_loop()
- print('\npost_order:');
- tree.post_order(tree.root)
- print('\npost_order_loop:');
- tree.post_order_loop()
- print('\npost_order_loop1:');
- tree.post_order_loop1()
- a11=NodeTu.NodeTu(6);
- a12=NodeTu.NodeTu(5);
- a13=NodeTu.NodeTu(4);
- a14=NodeTu.NodeTu(3);
- a15=NodeTu.NodeTu(2);
- a12=a11.next;
- a13=a14.next;
- a14=a15.next;
- a16=a11.next;
- print(a15.value);
- print(a11.value);
- a1 = NodeDu.NodeDu(6);
- b1 = NodeDu.NodeDu(5);
- b2 = NodeDu.NodeDu(2);
- c1 = NodeDu.NodeDu(4);
- c2 = NodeDu.NodeDu(1);
- c3 = NodeDu.NodeDu(1);
- d1 = NodeDu.NodeDu(3);
- d2 = NodeDu.NodeDu(0);
- a1.left = b1;
- a1.right = b2;
- b1.left = c1;
- b1.right = c2;
- b2.left = c3;
- c1.left = d1;
- c1.right = d2;
- s = [];
- def gos(node, path=[]):
- if node:
- path.append(node.value)
- if node.left:
- path1 = copy.copy(path)
- gos(node.left, path1)
- if node.right:
- path2 = copy.copy(path)
- gos(node.right, path2)
- else:
- s.append(copy.copy(path))
- gos(a1);
- print(s);
- #
- ptree = ParentedTree.fromstring('(ROOT (S (NP (JJ Congressional) \
- (NNS representatives)) (VP (VBP are) (VP (VBN motivated) \
- (PP (IN by) (NP (NP (ADJ shiny) (NNS money))))))) (. .))')
- def traverse(t):
- try:
- t.label()
- except AttributeError:
- return
- else:
- if t.height() == 2: #child nodes
- print(t.parent());
- return
- for child in t:
- traverse(child)
- tra=traverse(ptree);
- print(tra);
- ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \
- (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')
- leaf_values = ptree.leaves();
- if 'nice' in leaf_values:
- leaf_index = leaf_values.index('nice')
- tree_location = ptree.leaf_treeposition(leaf_index)
- print(tree_location);
- print(ptree[tree_location]);
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
level_order:
0
2
1
6
5
4
3
9
8
7
pre order:
0
1
3
7
8
4
9
2
5
6
pre order loop:
0
1
3
7
8
4
9
2
5
6
in_order:
7
3
8
1
9
4
0
5
2
6
in_order loop:
7
3
8
1
9
4
0
5
2
6
post_order:
7
8
3
9
4
1
5
6
2
0
post_order_loop:
7
8
3
9
4
1
5
6
2
0
post_order_loop1:
https://repo.continuum.io/archive/.winzip/
https://github.com/Rochester-NRT/RocAlphaGo
https://github.com/wrongu/
https://github.com/hiropppe/
https://gitter.im/Rochester-NRT/RocAlphaGo
http://www.nltk.org/nltk_data/
Python: tree data structure的更多相关文章
- [Algorithms] Tree Data Structure in JavaScript
In a tree, nodes have a single parent node and may have many children nodes. They never have more th ...
- 树状结构 Tree data structure in C#
delegate void TreeVisitor<T>(T nodeData); class NTree<T> { private T data; private Linke ...
- CDOJ 483 Data Structure Problem DFS
Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...
- 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
- LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design
字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith ...
- 211. Add and Search Word - Data structure design
题目: Design a data structure that supports the following two operations: void addWord(word) bool sear ...
- [LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- 【LeetCode】211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,211,搜索单词,前缀树,字典树 ...
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
随机推荐
- 使用Docker搭建CentOS 7 + Apache 2.4+ PHP7
从Docker Hub上Pull最新的CentOS 7镜像并新建容器 # sudo docker pull centos docker run -p 8082:80 --name centos_c - ...
- 人脸识别准备 -- 基于raspberry pi 3b + movidius
最近准备系统地学习一下深度学习和TensorFlow,就以人脸识别作为目的. 十年前我做过一些图像处理相关的项目和研究,涉及到图像检索.记得当时使用的是SIFT特征提取,该特征算子能很好地抵抗图像旋转 ...
- iOS逆向工程之Cycript
1.连接设备 打开一个终端,输入指令: iproxy 重新打开一个新的终端,输入指令: ssh -p root@127.0.0.1 这时候会提示输入密码:默认密码为“alpine”.这样就可以连接到设 ...
- 【leetcode】 算法题3 无重复字符的最长子串
问题 给定一个字符串,找出不含有重复字符的最长子串的长度. 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度 ...
- Oracle服务器和客户端安装在同一台机器的情况
最近重装了系统,所有的开发环境需要重新部署一下,因此重新安装了Oracle,结果原来没有问题,这一次又碰到了几个问题(tns12154和tns03505),让我好一搞啊.不过又重新对Oracle加深了 ...
- Linux Ubuntu部署web环境及项目tomcat+jdk+mysql
1,下载文件 在官网下载好 tomcat.jdk.mysql的linux压缩包 后缀名为.tar.gz 并通过xftp上传到服务器 或者直接通过linux命令 下在wget文件的下载地址 例如: wg ...
- kill 结束进程
kill 支持的信号 kill -1 重启进程 kill -9 终止进程 pkill 和 killall 的区别在于pkill 可以踢终端用户 pkill -9 -t tty1
- php函数式编程
// 函数式编程 $users = array( array('id' => 1, 'name' => 'abc1', 'age' => 29, '性别' => '男'), a ...
- 从github clone文件: Failed to receive SOCKS4 connect request ack.
安装了代理,能上网,也能从github上下载文件,就是无法从github上clone文件, 查了很久资料后,终于发现使用sudo可以解决问题.不过,不知道原因是什么? 比如:git clone htt ...
- python(30)——【random模块】【if __name__ =='__main__'】【os模块】
一.random模块(随机模块) 1.random 常用模块介绍 import random print(random.random()) #返回[0,1)之间的随机浮点数 print(random. ...