def test_print(): def convert_print(target): print(convert(target)) def convert_pprint(target): pprint(convert(target)) for invalid_argument in [1, 'foo']: with pytest.raises(ValueError) as err: pprint(invalid_argument) assert str(err.value) == 'Expecting a list or a node' for print_func in [pprint, convert_pprint]: with CaptureOutput() as output: print_func([]) assert output == [''] for print_func in [convert_print, pprint, convert_pprint]: with CaptureOutput() as output: print_func([1, 2]) assert output == ['', ' 1', ' / ', '2 ', ' '] with CaptureOutput() as output: print_func([1, None, 3]) assert output == ['', '1 ', ' \\ ', ' 3', ' '] with CaptureOutput() as output: print_func([1, 2, 3]) assert output == ['', ' 1 ', ' / \\ ', '2 3', ' '] with CaptureOutput() as output: print_func([1, 2, 3, None, 5]) assert output == [ '', ' __1 ', ' / \\ ', '2 3', ' \\ ', ' 5 ', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, None, 5, 6]) assert output == [ '', ' __1__ ', ' / \\ ', '2 3', ' \\ / ', ' 5 6 ', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, None, 5, 6, 7]) assert output == [ '', ' __1__ ', ' / \\ ', '2 3 ', ' \\ / \\ ', ' 5 6 7', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, 8, 5, 6, 7]) assert output == [ '', ' __1__ ', ' / \\ ', ' 2 3 ', ' / \\ / \\ ', '8 5 6 7', ' ' ] for _ in range(repetitions): bt = tree(height=10) with CaptureOutput() as output1: print(bt) assert output1 == str(bt).splitlines() assert output1 == stringify(bt).splitlines()
def printTree(tree): setup(node_init_func=lambda v: TreeNode(v), node_class=TreeNode, null_value=None, value_attr='data', left_attr='left', right_attr='right') pprint(tree) return
if node.value <= cur.value: prev = cur cur = cur.left else: prev = cur cur = cur.right if node.value <= prev.value: prev.left = node else: prev.right = node if __name__ == "__main__": n = int(input("what is height of tree?")) head1 = bst(n) pprint(head1) size = int(input("Enter the number of elements to create a subtree")) subt = BStree() for i in range(size): val = int(input("enter the node %d value" % (i + 1))) subt.insert(Node(val)) print("The input sub stree is") pprint(subt.root) if is_sub_tree(head1, subt.root): print("The tree headed %d is sub tree of the tree headed %d" % (subt.root.value, head1.value)) else: print("The tree headed %d is NOT a sub tree of the tree headed %d" % (subt.root.value, head1.value)) if rec_is_subtree(head1, subt.root):
from binarytree import Node, tree, bst, heap, pprint # Generate a random binary tree and return its root my_tree = tree(height=5, balanced=True) # Generate a random BST and return its root my_bst = bst(height=5) # Generate a random max heap and return its root my_heap = heap(height=3, max=True) # Pretty print the trees in stdout #pprint(my_tree) #pprint(my_bst) #pprint(my_heap) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) pprint(root)
from binarytree import tree, bst, heap, pprint # Generate a random binary tree and return its root my_tree = tree(height=5, balanced=False) # Generate a random BST and return its root my_bst = bst(height=5) # Generate a random max heap and return its root my_heap = heap(height=3, max=True) # Pretty print the trees in stdout pprint(my_tree) pprint(my_bst) pprint(my_heap)
# and do not overwrite a newer large node with an older smaller one # the tree is converted to a list for easy search values = bt.convert(n) if i in values: i_node = n if j in values: j_node = n # if not, assign them to nodes if not j_node: j_node = bt.Node(j) if not i_node: i_node = bt.Node(i) # finally, join the created or found nodes by the root # NOTE: make node values -1 to avoid distance and coordinate conflict # this could be solved by mapping the (i,j) coordinates to alphabetic names root = bt.Node("D({},{})={}".format(i, j, str(D[i][j]))) root.left = j_node root.right = i_node # place the node in front of the list # this naturally ensures that complete nodes are in front and incomplete nodes in the tail nodes.insert(0, root) pairs.remove((i, j)) return nodes[0] if __name__ == "__main__": bt.pprint(make_tree(test_matrix))
return root, True elif root.value == val1 or root.value == val2: if left or right: return root, True else: return root, False else: if left: return left, False elif right: return right, False else: return None, False if __name__ == "__main__": print("Python program to find the common ancestor of a tree") n = int(input("what is height of tree?")) my_tree = tree(n) print("The random tree of level %d" % n) pprint(my_tree) while 1: val1 = int(input("enter the value 1:")) val2 = int(input("enter the value 2:")) ans, res = find_anscestor(my_tree, val1, val2) if res: print("The common anscestor of %d and %d is %d" % (val1, val2, ans.value)) else: print("The common anscestor not found")
__author__ = 'harshul' from interactivepython.basic.tree import Node #using python package for binary tree: https://pypi.python.org/pypi/binarytree from binarytree import tree, pprint, inspect, convert, heapify mytree = tree(height=2, balanced=True) #pprint(mytree) my_list = [5, 4, 6, 3, 1, 2, 7, 8] # Convert the list into a tree and return its root my_tree = convert(my_list) pprint(my_tree) # Convert the list into a heap and return its root heapify(my_list) my_tree = convert(my_list) pprint(my_tree) # Convert the tree back to a list my_list = convert(my_tree) # Pretty-printing also works on lists pprint(my_list)
else: return lbh + isBlack(root) def isBlack(node): if node.color == 'Black': return 1 else: return 0 rand_arr = random.sample(range(100), 16) print(rand_arr) root = Node(rand_arr[0]) for x in rand_arr[1:16]: insert(x, root) pprint(root) print(root.inspect()) print(isAVL(root)) list = [87, 43, 44, 42, 23, 90, 24, 82, 76, 91, 71, 27, 89, 0, 48] my_tree = Node(31) for x in list[0:15]: insert(x, my_tree) pprint(my_tree) print("Height",height(my_tree)) print("Max Depth", maxdepth(my_tree)) print("Is AVL?", isAVL(my_tree)) color_black(my_tree) print("Black height, if valid?", blackheight(my_tree)) height_dis = [] AVL_dis = []
print("%s : level = %d" %(level_traversal.__name__, level)) return lt def level_traversal_rec(cur, lt, level): if cur: lt[level].append(cur) if cur.left or cur.right: lt.append(list()) level_traversal_rec(cur.left, lt, level+1) level_traversal_rec(cur.right, lt, level+1) if __name__=="__main__": n = int(input("what is height of tree?")) my_bst = bst(n) pprint(my_bst) height = find_height(my_bst) print("recursive : height of the tree is %d" %height) height = find_height_it(my_bst) print("iterative : height of the tree is %d" %height) lt= level_traversal(my_bst) print("Level traversal of the tree") for i in range(len(lt)): for j in range(len(lt[i])): print("%d " %lt[i][j].value, end="") print() lt = list() lt.append(list()) level_traversal_rec(my_bst, lt, 0) print("Level traversal of the tree recursive") for i in range(len(lt)):
from binarytree import tree, bst, pprint, inspect, convert my_bst = convert([8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]) pprint(my_bst) class Node: def __init__(self, value): self.right = None self.left = None self.value = value self.parent = None def find_max(node): if node is None: return while node.right: node = node.right return node def find_min(node): if node is None: return while node.left: node = node.left return node def set_parents(node): if node is None:
def display(self, msg): print(msg) pprint(self.root) self.print_preorder("AVL Tree in preorder with bfactors")
Q2[i1][i][j1][j] = float('inf') return Q2[i1][i][j1][j] if (bool(Q2[i1][i][j1][j])): return Q2[i1][i][j1][j] else: minimum = float('inf') for k in range(i1, i + 1): minimum = min( minimum, Q2f(i1, k, j1, p2[j]) + Qf(k + 1, i, p2[j] + 1, j - 1) + b) Q2[i1][i][j1][j] = min( Qf(i1, i, j1, j - 1) + a + b, Q2f(i1, i, j1, j - 1) + b, minimum) return Q2[i1][i][j1][j] for i1, j1 in itertools.product(range(1, size1 + 1), range(1, size2 + 1)): for i in range(i1, r1[i1] + 1): for j in range(j1, r2[j1] + 1): Q1[i1][i][j1][j] = Q1f(i1, i, j1, j) Q2[i1][i][j1][j] = Q2f(i1, i, j1, j) Q[i1][i][j1][j] = Qf(i1, i, j1, j) # print i1, i, j, j1 #print size1, size2 pprint(tree1), pprint(tree2) print Q[1][r1[1]][1][r2[1]]
def in_order(node): if node.left: for x in in_order(node.left): yield x yield node.value if node.right: for x in in_order(node.right): yield x def check_binary_search_tree_(root): traversed_tree = list(in_order(root)) for i in range(1, len(traversed_tree)): if traversed_tree[i] <= traversed_tree[i - 1]: return False return True if __name__ == '__main__': print('\n--- TREE ---') my_tree = tree(height=3, balanced=True) pprint(my_tree) print('In order: ', list(in_order(my_tree))) print('Is it a bst? : {}'.format(check_binary_search_tree_(my_tree))) print('\n--- BST ---') my_bst = bst(height=3) pprint(my_bst) print('In order: ', list(in_order(my_bst))) print('Is it a bst? : {}'.format(check_binary_search_tree_(my_bst)))
def display(self, msg): print(msg) pprint(self.root) self.print_preorder("Red Black tree in preorder with colors")
return leftpaths + rightpaths def all_paths(root, sum, paths): if root == None: return 0 path = list() rootpaths = paths_from_node(root, sum, 0, path) if rootpaths: paths.append(path) leftpaths = all_paths(root.left, sum, paths) rightpaths = all_paths(root.right, sum, paths) return rootpaths + leftpaths + rightpaths if __name__ == "__main__": n = int(input("what is height of tree?")) head = tree(n) print("The input binary tree is as follows") pprint(head) while True: sum = int(input("enter the value to find the all path sum")) pathlist = list() paths = all_paths(head, sum, pathlist) print("The number of paths for the sum %d are %d" % (sum, paths)) print("The path elements are") for i in range(len(pathlist)): print(pathlist[i])
def display(self, msg): print(msg) pprint(self.root)
def add(self, t, var, value, dtype, index=0): def solve_lower(var, value): from .model import Model lower_value = math.floor(value) m_lower = Model(dtype=dtype) m_lower.create_from_tableau(ex_tv=relaxedTV_lower) try: m_lower.add_lazy_constraint(var['x'] <= lower_value) return True, m_lower except InfeasibleError: return False, m_lower def solve_upper(var, value): from .model import Model upper_value = math.ceil(value) m_upper = Model(dtype=dtype) m_upper.create_from_tableau(ex_tv=relaxedTV_upper) try: m_upper.add_lazy_constraint(var['x'] >= upper_value) return True, m_upper except InfeasibleError: return False, m_upper def to_string(s): if isinstance(s, float): if np.isinf(s): return '' else: return str(s) else: return str(s) print("Branch and bound index", index) relaxedTV_lower = t.deepcopy() relaxedTV_upper = t.deepcopy() self.remove_from_tree(index) lower_feasible, lower_model = solve_lower(var, value) upper_feasible, upper_model = solve_upper(var, value) print("Solved lower and upper") self.add_left(index, lower_model) self.add_right(index, upper_model) obj_list = [to_string(x) for x in self.tree_obj] tree = convert(obj_list) pprint(tree) best_unexplored_model, best_index = self.get_best_unexplored() print("Best index", best_index) if best_unexplored_model: solved = best_unexplored_model.solve_mip(self, best_index) if solved: obj = best_unexplored_model.get_solution_object()[-1] if self.check_if_better(obj, best_unexplored_model): print("Found best", obj)
def convert_pprint(target): pprint(convert(target))
self.root = self.root.remove(k, None) setup(node_init_func=lambda v: AVLNode(v), node_class=AVLNode, null_value=None, value_attr='key', left_attr='left', right_attr='right') if __name__ == '__main__': avl = AVL() avl.insert(70) avl.insert(60) avl.insert(50) avl.insert(40) avl.insert(30) avl.insert(20) avl.insert(10) avl.insert(25) avl.insert(31) avl.remove(40) avl.remove(50) pprint(avl.root) avl.remove(25) pprint(avl.root) avl.remove(20) pprint(avl.root) avl.remove(10) pprint(avl.root)
cur = cur.right if not cur: flag = 0 cur = self.root if not cur: print("could not generate the random number") return 0 def get_randomnode_1(self): index = random.randint(0, self.root.size) while True: val = get_i_node(self.root, index) if val != None: return val if __name__ == "__main__": n = int(input("what is height of tree?")) head = bst(n) lt = convert(head) bshead = bs_tree() for i in range(len(lt)): if lt[i]: bshead.insert(knode(lt[i])) print("Input Binary tree is ") pprint(bshead.root) while True: input("enter key to genearte a random number") print("The random value = %d" % bshead.get_randomnode())
leftResult = [] rightResult = [] if root is not None: leftResult = [tree_diameter_o_n(root.left)] rightResult = [tree_diameter_o_n(root.right)] height = max(leftResult[0], rightResult[0]) + 1 rootDiameter = leftResult[0] + rightResult[0] + 1 finalDiameter = max(leftResult[1], rightResult[1], rootDiameter) d_and_h[0] = height d_and_h[1] = finalDiameter return d_and_h #testing above code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.right = Node(5) print(tree_diameter_o_n(root)) #testing with python's binarytree package random_tree = tree(4, False) pprint(random_tree) print(tree_diameter_o_n(random_tree))