Esempio n. 1
0
 def parse(cls, root: OrgNode, chap: str, sect: str) -> 'CardType':
     key, page = cls.keytitle(root)
     q, a = root.content
     assert q.heading.strip() == 'Question', q.heading
     assert a.heading.strip() == 'Solution', a.heading
     return Exercise(q=Tree.from_str(q.content),
                     a=Tree.from_str(a.content),
                     chap=chap,
                     sect=sect,
                     key=key,
                     page=page)
Esempio n. 2
0
 def parse(cls, root: OrgNode, chap: str, sect: str,
           part: str) -> 'CardType':
     key, page = cls.keytitle(root)
     term, def_ = root.content
     assert term.heading.strip() == 'Term', term.heading
     assert def_.heading.strip() == 'Def', def_.heading
     return Def(term=Tree.from_str(term.content),
                def_=Tree.from_str(def_.content),
                chap=chap,
                sect=sect,
                part=part,
                key=key,
                page=page)
Esempio n. 3
0
 def parse(cls, root: OrgNode, chap: str, sect: str,
           part: str) -> 'CardType':
     key, page = cls.keytitle(root)
     pp, pf = root.content
     assert pp.heading.strip() == 'Proposition'
     assert pf.heading.strip() == 'Proof'
     return Prop(prop=Tree.from_str(pp.content),
                 proof=Tree.from_str(pf.content),
                 chap=chap,
                 sect=sect,
                 part=part,
                 key=key,
                 page=page)
Esempio n. 4
0
 def parse(root: OrgNode, chap: str, sect: str, part: str) -> 'CardType':
     key = root.heading.replace('<', '').replace('>', '').strip()
     return Example(x=Tree.from_str(root.content),
                    chap=chap,
                    sect=sect,
                    part=part,
                    key=key)
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']
Esempio n. 6
0
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
Esempio n. 7
0
    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()
Esempio n. 8
0
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']
Esempio n. 9
0
    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)
Esempio n. 10
0
    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
Esempio n. 11
0
def param_card_edit(par_expr, decays, model_name, output_dir, param_dir = '../Cards', truncate = 2):
    # Resolve the symbolic expressions
    parameters = Tree.convert_parameters(par_expr)
    # Get parameter name
    par_suffix = ''
    for p in sorted(parameters.keys()):
        # Truncate values to n decimals in file name
        truncate_string = "{{0:.{}f}}".format(truncate)
        value_name = truncate_string.format(parameters[p])
        par_suffix += "{}{}_".format(p, value_name.replace(
            '.', 'p')).replace('p0_', '_').replace(' ', '')
    par_file_name = 'param_card_{}.dat'.format(par_suffix.rstrip('_'))
    # Build new card
    new_card = ''
    with open("{}/param_card_{}.dat".format(param_dir, model_name)) as card:
        for c in card:
            newstring = c
            comments = c.strip().split('#')
            # Change particle properties
            if len(comments) == 2:
                name = comments[1].strip()
                if name in parameters.keys():
                    leading_spaces = len(c) - len(c.lstrip(' '))
                    newstring = ' ' * leading_spaces + " ".join(
                        comments[0].split()[:-1]) + ' ' + str(parameters[name])\
                            + ' # ' + comments[1] + '\n'
            # Change decay properties
            if decays != None:
                if c.startswith("DECAY"):
                    pid = int(c.split()[1])
                    if pid in decays.keys():
                        dsplit = decays[pid].split()
                        br = dsplit[0]
                        products = " ".join(dsplit[1:])
                        nbody = len(dsplit[1:])
                        newstring += "   {}   {}   {}\n".format(
                            br, nbody, products)
            new_card += newstring
        # Print new card to file
        par_path = "{}/{}".format(output_dir, par_file_name)
        print(new_card, file = open(par_path, 'w'))
    return par_file_name
Esempio n. 12
0
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))
Esempio n. 13
0

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 lowestCommonAncestor(self, root, p, q):
        pathp = []
        pathq = []
        self.path_finder(root, pathp, p)
        self.path_finder(root, pathq, q)
        while len(pathp) and len(pathq):
            a = pathp.pop(0)
            b = pathq.pop(0)
            if a == b:
                return a
        return -1

    def path_finder(self, node, path, m):
        if not node:
            return False
        path.extend([node.val])
        if node.val == m:
            return True
        if self.path_finder(node.left, path, m):
            return True
        if self.path_finder(node.right, path, m):
            return True
        path.pop()
        return False


tree = Tree.creatTree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
print(Solution().lowestCommonAncestor(tree, 5, 1))
Esempio n. 15
0
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))
Esempio n. 16
0
        :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 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
Esempio n. 18
0
    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))
Esempio n. 19
0
        :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())
Esempio n. 20
0
        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))
Esempio n. 21
0
        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)))