def test_func(): test_cases = [{ 'input': { 'root': Tree([4, 2, 7, 1, 3]).root, 'val': 2 }, 'output': Tree([2, 1, 3]).root }, { 'input': { 'root': Tree([4, 2, 7, 1, 3]).root, 'val': 5 }, 'output': Tree([]).root }] solution = Solution_1() for test_case in test_cases: assert solution.searchBST(**test_case['input']) == test_case['output']
def template_parser(template_file): template = Tree() with open(template_file, 'r') as lines: for line in lines: line = line.rstrip() if not line.strip(): # ignore empty lines continue if line == '# Global config items beginning ignore': context = 'glb_beg_ign' template[context] = [] elif line == '# Global config items subset or exact ignore': context = 'glb_sub_ign' template[context] = [] elif line == '# Global config items beginning with': context = 'glb_beg_with' template[context] = [] elif line == '# Global config items': context = 'glb_cfg' template[context] = [] elif line == '# Grouped optional config items': key = uuid.uuid4().hex context = 'grp_opt' template['grp_opt'][key] = [] elif line == '# Global hierarchical config items': context = 'glb_hier' hierarc_cfg = [] template[context] = [] if '#' in line: continue if context == 'glb_hier': if line == '!': template['glb_hier'].append(hierarc_cfg) hierarc_cfg = [] else: hierarc_cfg.append(line) elif context == 'grp_opt': template['grp_opt'][key].append(line) else: template[context].append(line) return template
def inference(self, src_info): src_ids, src_lengths = src_info encoder_outputs, hidden = self.model.encoder(src_ids, src_lengths) # print(self.device) root = Tree(torch.LongTensor([self.trg_dictionary.SOS]).to(self.device)) mask = self.model.create_mask(src_ids) with torch.no_grad(): alpha = torch.ones(self.trg_dictionary.size()).to(src_ids) self.build_tree(root, hidden, encoder_outputs, mask, alpha, 0) return Trie(node = root).get_path()
def test_func(): test_cases = [{ 'input': { 'root': Tree([5, 3, 6, 2, 4, None, 7]).root, 'k': 9 }, 'expected': True, }, { 'input': { 'root': Tree([5, 3, 6, 2, 4, None, 7]).root, 'k': 28 }, 'expected': False }, { 'input': { 'root': Tree([2, 1, 3]).root, 'k': 4 }, 'expected': True }, { 'input': { 'root': Tree([2, 1, 3]).root, 'k': 1 }, 'expected': False }, { 'input': { 'root': Tree([2, 1, 3]).root, 'k': 3 }, 'expected': True }] # solution = Solution_1() # solution = Solution_2() solution = Solution_3() for test_case in test_cases: assert solution.findTarget(**test_case['input']) == test_case['expected']
def build_tree(self, tree_node, hidden, encoder_outputs, mask, alpha, depth): if depth > 20: return input = tree_node.value if input == self.trg_dictionary.EOS: return output, hidden, _ = self.model.decoder(input, hidden, encoder_outputs, mask) output = alpha * torch.sigmoid(output.squeeze(0)) for i in range(output.shape[0]): if output[i] > 0.5: child = Tree(torch.LongTensor([i]).to(self.device)) tree_node.children[i] = child for k, child in tree_node.children.items(): self.build_tree(child, hidden, encoder_outputs, mask, alpha, depth+1)
def predict(self, trees): trees = sorted(trees, key=lambda x: len(x.tokens)) output_trees = [] tree_idx = 0 for batch in self.batchify_X(trees): batch_trees = trees[tree_idx:(tree_idx + batch[0].shape[0])] batch_probs = self.model.predict_on_batch(batch) if not isinstance(batch_probs, list): batch_probs = [batch_probs] batch_preds = self.targets_factory.inverse_transform( batch_probs, batch_trees) for row_idx, old_tree in enumerate(batch_trees): row_probs = [p[row_idx] for p in batch_probs] row_preds = [p[row_idx] for p in batch_preds] emb = None new_tokens = [] for token_idx, token in enumerate(old_tree.tokens): new_token = deepcopy(token) for field, pred in zip(self.params.targets, row_preds): if field == 'sent': emb = pred else: new_token.fields[field] = pred[token_idx] new_tokens.append(new_token) output_trees.append( Tree( tree_id=old_tree.id, tokens=new_tokens, words=old_tree.words, comments=old_tree.comments, probs=row_probs if self.params.save_probs else None, emb=emb, )) tree_idx += 1 output_trees = sorted(output_trees, key=lambda x: x.id) return output_trees
if not node.left and not node.right: leaves.append(node.val) return leaves return leaves if __name__ == '__main__': s = Solution() # r1 = Tree('[3,5,1,6,2,9,8,null,null,7,4]') # r2 = Tree('[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]') # print(s.leafSimilar(r1, r2)) # # r3 = Tree('[1]') # r4 = Tree('[2]') # print(r3.get_nodes()) # print(r4.get_nodes()) # # print(s.leafSimilar(r3, r4)) r5 = Tree('[1,2,3]') r6 = Tree('[1,3,2]') print(r5.get_nodes()) print(r6.get_nodes()) print(s._tree_leaves(r5)) print(s._tree_leaves(r6)) print(s.leafSimilar(r5, r6))
:type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ return self._mergeTrees(t1, t2) def _mergeTrees(self, t1, t2): if not t1 and not t2: return None if not t1: return t2 if not t2: return t1 t1.val = (t1.val or 0) + (t2.val or 0) t1.left = self._mergeTrees(t1.left, t2.left) t1.right = self._mergeTrees(t1.right, t2.right) return t1 if __name__ == '__main__': s = Solution() t1 = Tree('[1,3,2,5]') t2 = Tree('[2,1,3,null,4,null,7]') t = s.mergeTrees(t1, t2) print(t.get_nodes())
def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ maxL = 0 def getMaxL(node, val): nonlocal maxL if not root: return 0 leftMaxL = getMaxL(node.left, node.val) rightMaxL = getMaxL(node.right, node.val) maxL = max(maxL, leftMaxL + rightMaxL) if (node.val == val): return max(leftMaxL, rightMaxL) + 1 else: return 0 if root: getMaxL(root, root.val) return maxL if __name__ == '__main__': s = Solution2() root = Tree('[4, 4, 4, 4, 4, 4, 4]') print(s.longestUnivaluePath(root))
class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ return self.getDepth(root) def getDepth(self, root): if root is None: return 0 if root.right is None: return self.getDepth(root.left) + 1 if root.left is None: return self.getDepth(root.right) + 1 l_height = self.getDepth(root.left) + 1 r_height = self.getDepth(root.right) + 1 return min(l_height, r_height) if __name__ == '__main__': s = Solution() root = Tree('[3,9,20,null,null,15,7]') print(s.minDepth(root))
class Solution(object): def distanceK(self, root, target, K): dfs = defaultdict(list) def connect(parent, child): if parent and child: dfs[parent.val].append(child.val) dfs[child.val].append(parent.val) if child.left: connect(child, child.left) if child.right: connect(child, child.right) connect(None, root) seemed = {target.val} bfs = [target.val] for _ in range(K): bfs = [y for x in bfs for y in dfs[x] if y not in seemed] seemed |= set(bfs) return bfs if __name__ == '__main__': s = Solution() root = Tree('[3,5,1,6,2,0,8,null,null,7,4]') print(s.distanceK(root, TreeNode(5), 2))
:type R: int :rtype: TreeNode """ if not node: return if node.val is not None and node.val < L: node = self._trimBST(node.right, L, R) elif node.val is not None and node.val > R: node = self._trimBST(node.left, L, R) if not node: return node.right = self._trimBST(node.right, L, R) node.left = self.trimBST(node.left, L, R) return node if __name__ == '__main__': s = Solution() root = Tree([1, 0, 2]) print(root.get_nodes()) print(s.trimBST(root, 1, 2).get_nodes()) root = Tree([3, 0, 4, None, 2, None, None, 1]) print(root.get_nodes()) print(s.trimBST(root, 1, 3).get_nodes())
def ios_xe_parser(configfile): """ This function parses banners, interface, vlan, global and hierarchical config items into a Python data structure """ with open(configfile, 'r') as lines: match = ReSearcher() tree = Tree() key_exceptions = ['ip vrf forwarding'] key_length = {1: ['hold-queue', 'standby', 'channel-group', 'description'], 2: ['switchport port-security', 'ip', 'spanning-tree', 'speed auto', 'srr-queue bandwidth'] } list_items = ['switchport trunk allowed vlan', 'standby', 'ip helper-address', 'logging event'] intf_parser = InterfaceParser(list_items, key_exceptions, key_length) context = '' global_cfg = [] hierarc_cfg = [] # Individual hierarchical config part hierarc_cfgs = [] # list with all individual hierarchical config parts for previous_line, line in prev_cur_generator(lines): if not line.strip(): # skip empty lines continue line = line.rstrip() if previous_line is not None: previous_line = previous_line.rstrip() if match(r'^hostname (.*)', line): hostname = format(match.group(1)) tree['hostname'] = hostname elif match(r'^interface (.*)', line): context = 'port' portindex = format(match.group(1)) tree['port'][portindex] = {} intf_parser.initialize_lists() elif match(r'^vlan ([\d,-]+)', line): context = 'vlan' for vlan in splitrange(format(match.group(1))): tree['vlan'][vlan] = {} elif match(r'^banner (\w+) (\S)', line): banner_type = format(match.group(1)) delimeter_char = format(match.group(2)) tree['banner'][banner_type]['delimeter_char'] = delimeter_char tree['banner'][banner_type]['lines'] = [] context = 'banner' elif context == 'port': if match(r'^ no (.*)', line): key = format(match.group(1)) value = format(match.group(0)) tree['port'][portindex][key] = value # interface items are stored with helper class elif match('^ .*', line): tree = intf_parser.parse_line(tree, portindex, line) elif match(r'!$', line): context = '' elif context == 'vlan': if match(r'^ name (.*)', line): tree['vlan'][vlan]['name'] = format(match.group(1)) elif match(r'!$', line): context = '' elif not line.startswith(' '): global_cfg.append(line) context = '' # Both line and previous line are global items elif line.lstrip() == line and context == '': if previous_line is None: pass elif not previous_line.startswith('!'): global_cfg.append(previous_line) # Previous line was beginning of hierarchical item elif line.lstrip() != line and context == '': hierarc_cfg = [] hierarc_cfg.append(previous_line) context = 'hierarc' # Both current and previous line belongs to hierarchical item elif line.lstrip() != line and context == 'hierarc': hierarc_cfg.append(previous_line) # Previous line was last hierarchical item elif line == '!' or line.startswith('') and context == 'hierarc': hierarc_cfg.append(previous_line) hierarc_cfgs.append(hierarc_cfg) context = '' # Previous line was last hierarchical item and directly followed # by start of another hierarchical item elif line.lstrip() == line and context == 'hierarc': hierarc_cfg.append(previous_line) hierarc_cfgs.append(hierarc_cfg) hierarc_cfg = [] elif context == 'banner' and not line.startswith(delimeter_char): tree['banner'][banner_type]['lines'].append(line) elif context == 'banner' and line.startswith(delimeter_char): context = '' tree['global_cfg'] = global_cfg tree['hierarc_cfgs'] = hierarc_cfgs return tree
class Solution: def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ res = [] if not root: return [] if not root.left and not root.right: res.append(str(root.val)) return res left = self.binaryTreePaths(root.left) for each in left: res.append(str(root.val) + '->' + each) right = self.binaryTreePaths(root.right) for each in right: res.append(str(root.val) + '->' + each) return res if __name__ == '__main__': s = Solution() root = Tree("[1,2,3,null,5]") print(s.binaryTreePaths(root))
left_val, left_tilt = self._findTilt(node.left) right_val, right_tilt = self._findTilt(node.right) return node.val + left_val + right_val, abs( left_val - right_val) + left_tilt + right_tilt class Solution2(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ def find(root): if not root: return 0, 0 ldif, lsm = find(root.left) rdif, rsm = find(root.right) return abs(lsm - rsm) + ldif + rdif, lsm + rsm + root.val d, s = find(root) return d if __name__ == '__main__': s = Solution() root = Tree([1, 2, 3]) print((s.findTilt(root)))