1. # 树结构
  2. from pythonds.basic.stack import Stack #pip install pythonds
  3. from pythonds.trees.binaryTree import BinaryTree
  4. from collections import defaultdict
  5. import json
  6.  
  7. #JSON-esque
  8. def tree():
  9. return defaultdict(tree)
  10.  
  11. def dicts(t):
  12. return {k: dicts(t[k]) for k in t}
  13.  
  14. #迭代
  15. def add(t, keys):
  16. for key in keys: t = t[key]
  17.  
  18. users = tree();
  19. users['harold']['username'] = 'hrldcpr'
  20. users['handler']['username'] = 'matthandlersux';
  21.  
  22. print(json.dumps(users));
  23.  
  24. taxonomy = tree();
  25. taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat']
  26. taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion']
  27. taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog']
  28. taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote']
  29. taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato']
  30. taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']
  31. taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']
  32.  
  33. print(dicts(taxonomy));
  34.  
  35. dtstr=add(taxonomy,'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
  36.  
  37. def buildParseTree(fpexp):
  38. fplist = fpexp.split()
  39. pStack = Stack()
  40. eTree = BinaryTree('')
  41. pStack.push(eTree)
  42. currentTree = eTree
  43. for i in fplist:
  44. if i == '(':
  45. currentTree.insertLeft('')
  46. pStack.push(currentTree)
  47. currentTree = currentTree.getLeftChild()
  48. elif i not in ['+', '-', '*', '/', ')']:
  49. currentTree.setRootVal(int(i))
  50. parent = pStack.pop()
  51. currentTree = parent
  52. elif i in ['+', '-', '*', '/']:
  53. currentTree.setRootVal(i)
  54. currentTree.insertRight('')
  55. pStack.push(currentTree)
  56. currentTree = currentTree.getRightChild()
  57. elif i == ')':
  58. currentTree = pStack.pop()
  59. else:
  60. raise ValueError
  61. return eTree
  62.  
  63. pt = buildParseTree("( ( 10 + 5 ) * 3 )")
  64. 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.

  1. import uuid;
  2.  
  3. #Python3.5
  4.  
  5. class TreeNode(object):
  6. def __init__(self, data = -1, lchild = None, rchild = None):
  7. self.data = data
  8. self.lchild = lchild
  9. self.rchild = rchild
  10.  
  11. class BinaryTree(object):
  12. def __init__(self):
  13. self.root = TreeNode()
  14.  
  15. def add(self, data):
  16. node = TreeNode(data)
  17. if self.isEmpty():
  18. self.root = node
  19. else:
  20. tree_node = self.root
  21. queue = []
  22. queue.append(self.root)
  23.  
  24. while queue:
  25. tree_node = queue.pop(0)
  26. if tree_node.lchild == None:
  27. tree_node.lchild = node
  28. return
  29. elif tree_node.rchild == None:
  30. tree_node.rchild = node
  31. return
  32. else:
  33. queue.append(tree_node.lchild)
  34. queue.append(tree_node.rchild)
  35.  
  36. def pre_order(self, start):
  37. node = start
  38. if node == None:
  39. return
  40.  
  41. print(node.data),
  42. if node.lchild == None and node.rchild == None:
  43. return
  44. self.pre_order(node.lchild)
  45. self.pre_order(node.rchild)
  46.  
  47. def pre_order_loop(self):
  48. if self.isEmpty():
  49. return
  50.  
  51. stack = []
  52. node = self.root
  53. while node or stack:
  54. while node:
  55. print(node.data),
  56. stack.append(node)
  57. node = node.lchild
  58. if stack:
  59. node = stack.pop()
  60. node = node.rchild
  61.  
  62. def in_order(self, start):
  63. node = start
  64. if node == None:
  65. return
  66. self.in_order(node.lchild)
  67. print(node.data),
  68. self.in_order(node.rchild)
  69.  
  70. def in_order_loop(self):
  71. if self.isEmpty():
  72. return
  73.  
  74. stack = []
  75. node = self.root
  76. while node or stack:
  77. while node:
  78. stack.append(node)
  79. node = node.lchild
  80.  
  81. if stack:
  82. node = stack.pop()
  83. print(node.data),
  84. node = node.rchild
  85.  
  86. def post_order(self, start):
  87. node = start
  88. if node == None:
  89. return
  90. self.post_order(node.lchild)
  91. self.post_order(node.rchild)
  92. print(node.data),
  93.  
  94. def post_order_loop(self):
  95. if self.isEmpty():
  96. return
  97.  
  98. node = self.root
  99. stack = []
  100. queue = []
  101. queue.append(node)
  102. while queue:
  103. node = queue.pop()
  104. if node.lchild:
  105. queue.append(node.lchild)
  106. if node.rchild:
  107. queue.append(node.rchild)
  108. stack.append(node)
  109. while stack:
  110. print(stack.pop().data),
  111.  
  112. #if lchild and rchild are None or lchild and rchild are printed, print the parent node node and pop out of the stack
  113. #else lchild and rchild push into the stack
  114. def post_order_loop1(self):
  115. if self.isEmpty():
  116. return
  117.  
  118. stack = []
  119. top = -1
  120. node = self.root
  121. stack.append(node)
  122. #we need to recognize the last printed node
  123. top += 1
  124. pre = None
  125. while stack:
  126. node = stack[-1]
  127. if node.lchild is None and node.rchild is None:
  128. print(node.data),
  129. pre = node
  130. top -= 1
  131. elif not pre and (node.lchild == pre or node.rchild == pre):
  132. print(node.data),
  133. pre = node
  134. top -= 1
  135. else:
  136. if node.rchild:
  137. if top < len(stack)-1:
  138. stack[top] = node.rchild
  139. else:
  140. stack.append(node.rchild)
  141. if node.lchild:
  142. if top < len(stack)-1:
  143. stack[top] = node.lchild
  144. else:
  145. stack.append(node.lchild)
  146.  
  147. def level_order(self):
  148. node = self.root
  149. if node == None:
  150. return
  151.  
  152. queue = []
  153. queue.append(node)
  154.  
  155. while queue:
  156. node = queue.pop(0)
  157. print(node.data),
  158. if node.rchild:
  159. queue.append(node.rchild)
  160. if node.lchild:
  161. queue.append(node.lchild)
  162. print
  163.  
  164. def isEmpty(self):
  165. return True if self.root.data == -1 else False
  166.  
  167. class NodeTu:
  168. def __init__(self, value, next=None):
  169. self.value = value;
  170. self.next = next;
  171.  
  172. class NodeDu:
  173. def __init__(self, value, left=None, right=None):
  174. self.value = value
  175. self.left = left
  176. self.right = right

  测试:

  1. import nltk;
  2. import pandas;
  3. import matplotlib;
  4. import math;
  5. import os;
  6. import unittest;
  7. #from nltk.parse.featurechart import trees
  8. import NodeDu;
  9. import copy;
  10. import NodeTu;
  11. import TreeNode;
  12. from nltk.tree import ParentedTree;
  13.  
  14. #Python 3.5
  15.  
  16. #from platform import node
  17.  
  18. #1. tree data structure
  19. arr = []
  20. for i in range(10):
  21. arr.append(i)
  22. print(arr);
  23.  
  24. tree =TreeNode.BinaryTree();
  25. for i in arr:
  26. tree.add(i)
  27. print('level_order:');
  28. tree.level_order();
  29. print('pre order:');
  30. tree.pre_order(tree.root)
  31. print('\npre order loop:');
  32. tree.pre_order_loop()
  33. print('\nin_order:');
  34. tree.in_order(tree.root)
  35. print('\nin_order loop:');
  36. tree.in_order_loop()
  37. print('\npost_order:');
  38. tree.post_order(tree.root)
  39. print('\npost_order_loop:');
  40. tree.post_order_loop()
  41. print('\npost_order_loop1:');
  42. tree.post_order_loop1()
  43.  
  44. a11=NodeTu.NodeTu(6);
  45. a12=NodeTu.NodeTu(5);
  46. a13=NodeTu.NodeTu(4);
  47. a14=NodeTu.NodeTu(3);
  48. a15=NodeTu.NodeTu(2);
  49.  
  50. a12=a11.next;
  51. a13=a14.next;
  52. a14=a15.next;
  53.  
  54. a16=a11.next;
  55.  
  56. print(a15.value);
  57. print(a11.value);
  58.  
  59. a1 = NodeDu.NodeDu(6);
  60. b1 = NodeDu.NodeDu(5);
  61. b2 = NodeDu.NodeDu(2);
  62. c1 = NodeDu.NodeDu(4);
  63. c2 = NodeDu.NodeDu(1);
  64. c3 = NodeDu.NodeDu(1);
  65. d1 = NodeDu.NodeDu(3);
  66. d2 = NodeDu.NodeDu(0);
  67.  
  68. a1.left = b1;
  69. a1.right = b2;
  70. b1.left = c1;
  71. b1.right = c2;
  72. b2.left = c3;
  73. c1.left = d1;
  74. c1.right = d2;
  75.  
  76. s = [];
  77.  
  78. def gos(node, path=[]):
  79. if node:
  80. path.append(node.value)
  81. if node.left:
  82. path1 = copy.copy(path)
  83. gos(node.left, path1)
  84. if node.right:
  85. path2 = copy.copy(path)
  86. gos(node.right, path2)
  87. else:
  88. s.append(copy.copy(path))
  89.  
  90. gos(a1);
  91. print(s);
  92.  
  93. #
  94. ptree = ParentedTree.fromstring('(ROOT (S (NP (JJ Congressional) \
  95. (NNS representatives)) (VP (VBP are) (VP (VBN motivated) \
  96. (PP (IN by) (NP (NP (ADJ shiny) (NNS money))))))) (. .))')
  97.  
  98. def traverse(t):
  99. try:
  100. t.label()
  101. except AttributeError:
  102. return
  103. else:
  104. if t.height() == 2: #child nodes
  105. print(t.parent());
  106. return
  107.  
  108. for child in t:
  109. traverse(child)
  110.  
  111. tra=traverse(ptree);
  112. print(tra);
  113.  
  114. ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \
  115. (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')
  116.  
  117. leaf_values = ptree.leaves();
  118.  
  119. if 'nice' in leaf_values:
  120. leaf_index = leaf_values.index('nice')
  121. tree_location = ptree.leaf_treeposition(leaf_index)
  122. print(tree_location);
  123. 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的更多相关文章

  1. [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 ...

  2. 树状结构 Tree data structure in C#

    delegate void TreeVisitor<T>(T nodeData); class NTree<T> { private T data; private Linke ...

  3. CDOJ 483 Data Structure Problem DFS

    Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...

  4. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  5. 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  ...

  6. 211. Add and Search Word - Data structure design

    题目: Design a data structure that supports the following two operations: void addWord(word) bool sear ...

  7. [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 ...

  8. 【LeetCode】211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,211,搜索单词,前缀树,字典树 ...

  9. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

随机推荐

  1. 使用Docker搭建CentOS 7 + Apache 2.4+ PHP7

    从Docker Hub上Pull最新的CentOS 7镜像并新建容器 # sudo docker pull centos docker run -p 8082:80 --name centos_c - ...

  2. 人脸识别准备 -- 基于raspberry pi 3b + movidius

    最近准备系统地学习一下深度学习和TensorFlow,就以人脸识别作为目的. 十年前我做过一些图像处理相关的项目和研究,涉及到图像检索.记得当时使用的是SIFT特征提取,该特征算子能很好地抵抗图像旋转 ...

  3. iOS逆向工程之Cycript

    1.连接设备 打开一个终端,输入指令: iproxy 重新打开一个新的终端,输入指令: ssh -p root@127.0.0.1 这时候会提示输入密码:默认密码为“alpine”.这样就可以连接到设 ...

  4. 【leetcode】 算法题3 无重复字符的最长子串

      问题      给定一个字符串,找出不含有重复字符的最长子串的长度. 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度 ...

  5. Oracle服务器和客户端安装在同一台机器的情况

    最近重装了系统,所有的开发环境需要重新部署一下,因此重新安装了Oracle,结果原来没有问题,这一次又碰到了几个问题(tns12154和tns03505),让我好一搞啊.不过又重新对Oracle加深了 ...

  6. Linux Ubuntu部署web环境及项目tomcat+jdk+mysql

    1,下载文件 在官网下载好 tomcat.jdk.mysql的linux压缩包 后缀名为.tar.gz 并通过xftp上传到服务器 或者直接通过linux命令 下在wget文件的下载地址 例如: wg ...

  7. kill 结束进程

    kill 支持的信号 kill -1 重启进程 kill -9 终止进程 pkill 和 killall 的区别在于pkill 可以踢终端用户 pkill  -9  -t tty1

  8. php函数式编程

    // 函数式编程 $users = array( array('id' => 1, 'name' => 'abc1', 'age' => 29, '性别' => '男'), a ...

  9. 从github clone文件: Failed to receive SOCKS4 connect request ack.

    安装了代理,能上网,也能从github上下载文件,就是无法从github上clone文件, 查了很久资料后,终于发现使用sudo可以解决问题.不过,不知道原因是什么? 比如:git clone htt ...

  10. python(30)——【random模块】【if __name__ =='__main__'】【os模块】

    一.random模块(随机模块) 1.random 常用模块介绍 import random print(random.random()) #返回[0,1)之间的随机浮点数 print(random. ...