Beispiel #1
0
def main():
    # An example use of 'build_tree' and 'predict'
    df_train = clean('horseTrain.txt')
    attributes = [
        'K', 'Na', 'CL', 'HCO', 'Endotoxin', 'Anioingap', 'PLA2', 'SDH',
        'GLDH', 'TPP', 'Breath rate', 'PCV', 'Pulse rate', 'Fibrinogen',
        'Dimer', 'FibPerDim'
    ]
    dec_tree = Tree(df_train, attributes, 'Outcome')
    print("Building the tree...")
    time1 = time.time()
    dec_tree.build_tree()
    time2 = time.time()
    print("Time spent to build the tree %.2f seconds" % (time2 - time1))
    print("Finish building the tree...")
    time.sleep(1)

    print("Shape of Tree ...")
    dec_tree.print_tree()
    time.sleep(1)

    print("Accuracy of test data ... ")
    df_test = clean('horseTest.txt')
    print(dec_tree.predict(df_test))
    print(df_test['Outcome'])
def test_Tree_search_for_2():
    _tree = Tree(1)
    _tree.head.add_child(2)
    _tree.head.add_child(3)
    _tree.head.get_children()[0].add_child(4)
    _tree.head.get_children()[0].add_child(5)
    _tree.print_tree()
    assert _tree.search_for(6) == False
Beispiel #3
0
 def test_unbalanced(self):
     """
     Test a unbalanced tree.
     :return:
     """
     tree = Tree()
     tree.add(10)
     tree.add(11)
     tree.add(12)
     tree.add(13)
     result = tree.print_tree(tree.root)
     assert result == [[
         '|', '|', '|', '|', '|', '|', '|', '10', '|', '|', '|', '|', '|',
         '|', '|'
     ],
                       [
                           '|', '|', '|', '|', '|', '|', '|', '|', '|', '|',
                           '|', '11', '|', '|', '|'
                       ],
                       [
                           '|', '|', '|', '|', '|', '|', '|', '|', '|', '|',
                           '|', '|', '|', '12', '|'
                       ],
                       [
                           '|', '|', '|', '|', '|', '|', '|', '|', '|', '|',
                           '|', '|', '|', '|', '13'
                       ]]
Beispiel #4
0
 def test_root_none(self):
     """
     Test when the root is none.
     :return:
     """
     tree = Tree()
     result = tree.print_tree(tree.root)
     assert result == []
Beispiel #5
0
def syntax(fname):
    lexems = lexer(fname)
    table = [{
        'num': 0,
        'name': 'signal-program',
        'code': [-1],
        'at': 1,
        'af': 1
    }, {
        'num': 1,
        'name': 'program',
        'code': [401],
        'at': 0,
        'af': 1
    }, {
        'num': 2,
        'name': 'program',
        'code': [-44],
        'at': 0,
        'af': 1
    }, {
        'num': 3,
        'name': 'program',
        'code': [59],
        'at': 0,
        'af': 1
    }, {
        'num': 4,
        'name': 'program',
        'code': [-6],
        'at': 0,
        'af': 1
    }, {
        'num': 5,
        'name': 'program',
        'code': [59],
        'at': 1,
        'af': 1
    }, {
        'num': 6,
        'name': 'block',
        'code': [402],
        'at': 0,
        'af': 1
    }, {
        'num': 7,
        'name': 'block',
        'code': [-9],
        'at': 0,
        'af': 1
    }, {
        'num': 8,
        'name': 'block',
        'code': [403],
        'at': 1,
        'af': 1
    }, {
        'num': 9,
        'name': 'statements-list',
        'code': [-12],
        'at': 0,
        'af': 1
    }, {
        'num': 10,
        'name': 'statements-list',
        'code': [-9],
        'at': 1,
        'af': 0
    }, {
        'num': 11,
        'name': 'statements-list',
        'code': [],
        'at': 1,
        'af': 1
    }, {
        'num': 12,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 13,
        'name': 'statement',
        'code': [58],
        'at': 0,
        'af': 1
    }, {
        'num': 14,
        'name': 'statement',
        'code': [-12],
        'at': 1,
        'af': 0
    }, {
        'num': 15,
        'name': 'statement',
        'code': [-43],
        'at': 0,
        'af': 1
    }, {
        'num': 16,
        'name': 'statement',
        'code': [301],
        'at': 0,
        'af': 1
    }, {
        'num': 17,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 18,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 19,
        'name': 'statement',
        'code': [-44],
        'at': 0,
        'af': 1
    }, {
        'num': 20,
        'name': 'statement',
        'code': [46],
        'at': 0,
        'af': 1
    }, {
        'num': 21,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 22,
        'name': 'statement',
        'code': [404],
        'at': 0,
        'af': 1
    }, {
        'num': 23,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 24,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 25,
        'name': 'statement',
        'code': [405],
        'at': 0,
        'af': 1
    }, {
        'num': 26,
        'name': 'statement',
        'code': [-43],
        'at': 0,
        'af': 1
    }, {
        'num': 27,
        'name': 'statement',
        'code': [44],
        'at': 0,
        'af': 1
    }, {
        'num': 28,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 29,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 30,
        'name': 'statement',
        'code': [406],
        'at': 0,
        'af': 1
    }, {
        'num': 31,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 32,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 33,
        'name': 'statement',
        'code': [407],
        'at': 0,
        'af': 1
    }, {
        'num': 34,
        'name': 'statement',
        'code': [-42],
        'at': 0,
        'af': 1
    }, {
        'num': 35,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 36,
        'name': 'statement',
        'code': [408],
        'at': 0,
        'af': 1
    }, {
        'num': 37,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 38,
        'name': 'statement',
        'code': [59],
        'at': 1,
        'af': 0
    }, {
        'num': 39,
        'name': 'statement',
        'code': [302],
        'at': 0,
        'af': 1
    }, {
        'num': 40,
        'name': 'statement',
        'code': [54],
        'at': 0,
        'af': 1
    }, {
        'num': 41,
        'name': 'statement',
        'code': [303],
        'at': 1,
        'af': 1
    }, {
        'num': 42,
        'name': 'unsigned-integer',
        'code': [range(500, 600)],
        'at': 1,
        'af': 1
    }, {
        'num': 43,
        'name': 'variable-identifier',
        'code': [-45],
        'at': 1,
        'af': 1
    }, {
        'num': 44,
        'name': 'procedure-identifier',
        'code': [-45],
        'at': 1,
        'af': 1
    }, {
        'num': 45,
        'name': 'identifier',
        'code': [range(1000, 2000)],
        'at': 1,
        'af': 1
    }, {
        'num': 46,
        'name': 'actual-arguments',
        'code': [40],
        'at': 0,
        'af': 1
    }, {
        'num': 47,
        'name': 'actual-arguments',
        'code': [-43],
        'at': 0,
        'af': 1
    }, {
        'num': 48,
        'name': 'actual-arguments',
        'code': [-51],
        'at': 0,
        'af': 1
    }, {
        'num': 49,
        'name': 'actual-arguments',
        'code': [41],
        'at': 1,
        'af': 0
    }, {
        'num': 50,
        'name': 'actual-arguments',
        'code': [],
        'at': 1,
        'af': 1
    }, {
        'num': 51,
        'name': 'actual-arguments-list',
        'code': [-43],
        'at': 0,
        'af': 1
    }, {
        'num': 52,
        'name': 'actual-arguments-list',
        'code': [-51],
        'at': 1,
        'af': 0
    }, {
        'num': 53,
        'name': 'actual-arguments-list',
        'code': [],
        'at': 1,
        'af': 1
    }, {
        'num': 54,
        'name': 'assembly-insert-file-identifier',
        'code': [-45],
        'at': 1,
        'af': 0
    }]

    tree = Tree()
    stack = []
    stack.append(table[0])
    lxm_itr = 0
    direction = 1
    stage = {"at": 0, "af": 0}
    while stack:
        if direction == 1:
            if stack[len(stack) - 1]['code'][0] < 0:
                stack.append(table[-1 * stack[len(stack) - 1]['code'][0]])
                tree.add(stack[len(stack) - 1]['name'])
                direction = 1
                continue
            if stack[len(stack) -
                     1]['code'][0] > 0:  #and stack[len(stack)-1]['num'] < 140:
                if lexems[lxm_itr] in stack[len(stack) - 1]['code']:
                    discription = ''
                    for key, word in dic_of_int_const.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    for key, word in dic_of_idents.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    for key, word in dic_of_complex_const.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    for key, word in dic_of_float_const.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    for key, word in key_words.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    for key, word in dm_dic.items():
                        if word == lexems[lxm_itr]:
                            discription = key
                    # print(lexems[lxm_itr], '-', discription)
                    tree.add(discription)
                    lxm_itr += 1
                    stage["at"] = 1
                    stage["af"] = 0
                else:
                    tree.add("error")
                    stage["at"] = 0
                    stage["af"] = 1
                direction = 0
                continue
            else:
                if lexems[lxm_itr] not in stack[len(stack) - 1]['code']:
                    stage["at"] = 1
                    stage["af"] = 0
                    tree.add("empty")
                else:
                    tree.add("not empty")
                    stage["at"] = 0
                    stage["af"] = 1
                direction = 0
                continue
        else:
            if direction == 0:
                if stack[len(stack) - 1]['code'][0] > 0:
                    #     return from stack up, stack pop and stack++
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 0 and stage["af"] == 0:
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        direction = 0
                        continue
                    #     return from stack up
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 0:
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        direction = 0

                        continue
                    #     return error and stop process
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 1:
                        if len(stack) == 1:
                            print("Error!")
                            exit()
                        else:
                            stack.pop()
                            tree.current_element = tree.current_element.parent_element
                            direction = 0
                            continue
                    #     return error and stop process
                    if stack[len(stack) -
                             1]['at'] == 0 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 1:
                        if len(stack) == 1:
                            print("Error!")
                            exit()
                        else:
                            stack.pop()
                            tree.current_element = tree.current_element.parent_element
                            direction = 0
                            continue
                    #     next line(stack++)
                    if stack[len(stack) -
                             1]['at'] == 0 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 0:
                        index_table = stack[len(stack) - 1]['num'] + 1
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        stack.append(table[index_table])
                        direction = 1
                        continue
                    #     next line(stack++)
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 0 and stage["af"] == 1:
                        index_table = stack[len(stack) - 1]['num'] + 1
                        stack.pop()
                        tmp_elem = tree.current_element
                        tree.current_element = tree.current_element.parent_element
                        tree.current_element.leaves.remove(tmp_elem)
                        stack.append(table[index_table])
                        tree.add(stack[len(stack) - 1]['name'])
                        direction = 1
                        continue
                if stack[len(stack) - 1]['code'][0] < 0:
                    #     return from stack up, stack pop and stack++
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 0 and stage["af"] == 0:
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        direction = 0
                        continue
                    #     return from stack up
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 0:
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        direction = 0
                        continue
                    #     return error and stop process
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 1:
                        if len(stack) == 1:
                            print("Error!")
                            exit()
                        else:
                            stack.pop()
                            tree.current_element = tree.current_element.parent_element
                            direction = 0
                            continue
                    #     return error and stop process
                    if stack[len(stack) -
                             1]['at'] == 0 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 1:
                        if len(stack) == 1:
                            print("Error!")
                            exit()
                        else:
                            stack.pop()
                            tree.current_element = tree.current_element.parent_element
                            direction = 0
                            continue
                    #     next line(stack++)
                    if stack[len(stack) -
                             1]['at'] == 0 and stage["at"] == 1 and stack[
                                 len(stack) -
                                 1]['af'] == 1 and stage["af"] == 0:
                        index_table = stack[len(stack) - 1]['num'] + 1
                        stack.pop()
                        tree.current_element = tree.current_element.parent_element
                        stack.append(table[index_table])
                        direction = 1
                        continue
                    #     next line(stack++)
                    if stack[len(stack) -
                             1]['at'] == 1 and stage["at"] == 0 and stack[
                                 len(stack) -
                                 1]['af'] == 0 and stage["af"] == 1:
                        index_table = stack[len(stack) - 1]['num'] + 1
                        stack.pop()
                        tmp_elem = tree.current_element
                        tree.current_element = tree.current_element.parent_element
                        tree.current_element.leaves.remove(tmp_elem)
                        stack.append(table[index_table])
                        tree.add(stack[len(stack) - 1]['name'])
                        direction = 1
                        continue
    print('=========================================')
    tree.print_tree()
    print('=========================================')
    tree.listing()
    return tree
Beispiel #6
0
        if midnode.len_child() > 0:
            mid_list = []
            for node in midnode.child:
                mid_list.append(self.genrate_condition(node))
            if len(mid_list) != 0:
                res += " and " + self.str_join(" and ", mid_list)

        return res


if __name__ == '__main__':

    map_list = [['show', 1.0, 'root', 'show'], ['100', 1.0, 'VN', '100'],
                ['1000', 1.0, 'VN', '1000'], ['not', 1.0, 'CN', 'not'],
                ['less', 1.0, 'ON', '<'], ['and', 1.0, 'CN', 'and'],
                ['elctconsumption', 1.0, 'NN', 'elctConsumption'],
                ['shanghai', 1.0, 'VN', 'Shanghai', 'cityName'],
                ['>', 1.0, 'ON', '>']]
    ON_VN_map = {'100': '>', '1000': '<'}

    mylis = [
        'show', 'elctConsumption', 'Shanghai',
        ['and', ['>', '100'], ['not', ['<', '1000']]]
    ]

    metree = Tree(mylis, map_list, ON_VN_map)
    metrans = translate(metree.tree, map_list, ON_VN_map)
    metree.print_tree(metree.tree)

    print(metrans.generate_sql(metree.tree))
Beispiel #7
0
    opattern = exclude_paths(arguments["--exclude"])
    url = os.environ.get('GITLAB_URL', arguments["--gitlab"])
    token = os.environ.get('GITLAB_TOKEN', arguments["--token"])

    gitlab = auth_gitlab(url, token)
    arguments["gitlab"] = gitlab
    arguments["token"] = token
    arguments["url_base"] = url
    tree = Tree(url,
                gitlab,
                includes=ipattern,
                excludes=opattern,
                concurrency=int(arguments["--concurrency"]),
                in_file=in_file,
                method=arguments["--method"])
    log.debug("Reading projects tree from gitlab at [{url}]".format(url=url))
    tree.load_tree()
    if tree.is_empty():
        log.fatal("The tree is empty, check your include/exclude patterns")
        sys.exit(1)

    if arguments["--dry-run"]:
        tree.print_tree(arguments["--format"])
    else:
        if arguments["branch"]:
            tree.sync_tree("branch", arguments)
        if arguments["clone"]:
            tree.sync_tree("clone", arguments)
        if arguments["plugins"]:
            tree.sync_tree("plugins", arguments)
Beispiel #8
0
def main():
    usage = 'python foldify.py source_file [destination_file] [--label] [--help]'
    description = '''
    ======================================================
    Foldify - CLI tools for managing directory Trees.
    Version: {version}
    Author: {author}

    Operations:

    ## Print a directory tree ##
    $ foldify directory1

    ## Label empty Folder in tree ##
    $ foldify directory1 --label [update, remove]

    ## Copy a directory Tree ##
    $ foldify directory1 directory2

    ## Create Json from a directory ##
    $ foldify directory1 directory1.json

    ## Create Directory from json ##
    $ foldify directory1.json directory1

    ======================================================
    '''.format(version=__version__, author=__author__)

    parser = argparse.ArgumentParser(prog='Foldify', description=description,
                                     usage=usage,
                                     formatter_class=help_formatter,
                                     )

    parser.add_argument('source_file', type=str,
                        help='Source filepath.')

    parser.add_argument('-l', '--label', choices=['update', 'remove'],
                        help='Adds Label _EMPTY to empty folders.')

    parser.add_argument('--custom-label', help='Customizes empty label.')

    parser.add_argument('dest_file', type=str, nargs='?',
                        help='Destination filepath.')

    parser.add_argument('-v', '--verbose', action='store_true')

    args_dict = vars(parser.parse_args())
    globals().update(args_dict)
    # print(args_dict)

    if verbose:
        enable_debug()

    # ensure source_file exists, if not exit.
    exists = os.path.exists
    if not exists(source_file):
        print('=' * 40)
        parser.print_help()
        print('=' * 40)
        print('ERROR: source_file does not exist.')
        sys.exit()

    #  If no dest_file, print source_tree
    if not dest_file:
        if label:
            t = generate_transactions(path=source_file, label=custom_label,
                                      remove_all=bool(label == 'remove'))
            apply_transactions(t)
        else:
            tree = Tree(source_file, json=is_json(source_file))
            print('=' * 40)
            tree.print_tree()
            print('=' * 40)
        sys.exit('Done.')

    # if dest_file exists, prompt for overwite before continuing.
    if exists(dest_file):
        if label:
            sys.exit('Must use only source_file with --label option.')
        if input('WARNING: dest_file already exists. Overwrite? (y/n)') != 'y':
            print('Exiting.')
            print('=' * 40)
            sys.exit()

    # Copy folder, json from dir, or dir from json, depending on formats.
    tree = Tree(source_file, json=is_json(source_file))
    write_dest = tree.write_json if is_json(dest_file) else tree.write_tree
    write_dest(dest_file)
Beispiel #9
0
class DicomSR(object):
    def __init__(self, report_type="", id_ontology=-1):
        self.report_type = report_type
        self.id_ontology = id_ontology
        self.report = Tree()

    def imprime(self):
        """ Pretty print of a report """
        print u"\n ------ {0} ---------- \n".format(self.report_type)
        self.report.print_tree(0)

    def add_node(self, node, parent):
        self.report.add_node(node, parent)

    def get_ontology(self):
        """ Return current report ontology """
        return self.id_ontology

    def get_flat_data(self):
        flat = {}
        self.report.get_flat_tree(flat)
        return flat

    def get_root(self):
        return self.report.value

    def get_data_from_report(self, template_type, languages=None,
                             position=None, cardinality=None):
        """ Return data from the report in a dictionary

        Keyword arguments:
        languages -- list of languages supported in the  report.
        template_type -- indicates the template type and
                         therefore the information to extract from the report.
        self -- Dict Report with the information extracted from the dicom XML.
        position -- dictionary where it's stored parent and
                    its children position

        """
        substitution_words = {}
        if (template_type in MULTIPLE_PROPERTIES.keys()):
            if (template_type == DICOM_LEVEL):
                # Get keys for this template
                levels_tag = MULTIPLE_PROPERTIES[DICOM_LEVEL][0]
                attrs_tag = MULTIPLE_PROPERTIES[DICOM_LEVEL][1]
                level_name = MULTIPLE_PROPERTIES[DICOM_LEVEL][3]
                level_num = MULTIPLE_PROPERTIES[DICOM_LEVEL][2]
                code = MULTIPLE_PROPERTIES[DICOM_LEVEL][4]
                meaning = MULTIPLE_PROPERTIES[DICOM_LEVEL][5]
                #Init dictinary will hold the substitution.
                # Keys are language code and values  contains
                # values to fill the template
                for language in languages:
                    substitution_words[language] = {
                        levels_tag: [],
                        attrs_tag: []}
                #Get container's concept and its attributes
                containers = []
                attributes = []
                self.report.get_set_data(containers, attributes)
                for container in containers:
                    ontology = get_ontology_level(
                        ontology_id=self.get_ontology(),
                        tree_level=container.get_level(),
                        languages_tag=language)
                    for language in languages:
                        aux = {}
                        aux[level_num] = container.get_level()
                        aux[level_name] = (unicode(ontology, "utf-8"))
                        aux[code] = container.get_code().lower()
                        aux[meaning] = container.get_meaning()[language]
                        substitution_words[language][levels_tag].\
                            append(aux.copy())
                for attribute in attributes:
                    for language in languages:
                        aux = {}
                        aux[code] = attribute.code.lower()
                        aux[meaning] = attribute.meaning[language]
                        substitution_words[language][attrs_tag].\
                            append(aux.copy())

            elif (template_type == CHILDREN_ARRAYS):
                nodes_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][0]
                parent_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][1]
                children_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][2]
                # Get a flat version of the report
                # TODO: check if the flat version of the tree is
                # always the same
                flat = {}
                self.report.get_flat_tree(flat)
                #Delete leaf items. They are not needed
                flat = {key: flat[key] for key in flat if flat[key]}
                if languages:
                    for language in languages:
                        substitution_words[language] = {nodes_tag: []}

                    for parent, children in flat.iteritems():
                        for language in languages:
                            aux = {parent_tag: parent.get_code().lower(),
                                   children_tag: []}
                            position = 0
                            for child in children:
                                aux[children_tag].append(
                                    child.get_meaning()[language])
                                #print parent.get_schema_code()
                                #print child.get_schema_code(), position
                                position += 1
                            substitution_words[language][nodes_tag].append(aux)
                else:
                    for parent, children in flat.iteritems():
                        p_code = (parent.get_schema().lower() + '_' 
                                  + parent.get_code().lower())
                        position[p_code] = {}
                        cardinality[p_code] = {}
                        pos = 0
                        for child in children:
                            position[p_code][pos] = child.get_schema_code()
                            cardinality[p_code][pos] = child.get_max_cardinality()
                            pos += 1

            elif (template_type == CODE_ARRAYS):
                #TODO: Change comment on this template to make it different
                #from CHILDREN_ARRAYS
                nodes_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][0]
                parent_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][1]
                children_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][2]
                for language in languages:
                    substitution_words[language] = {nodes_tag: []}
                codes = self.report.get_code_containers()
                for code in codes:
                    for language in languages:
                        aux = {parent_tag: code.code.lower(), children_tag: []}
                        for option in code.options:
                            aux[children_tag].append(
                                option.meaning[language])
                        substitution_words[language][nodes_tag].append(aux)

        return substitution_words
Beispiel #10
0
from tree import TreeNode, Tree
""" Runtime would be O(m) where m is
    the number of nodes. It would have
    to traverse through every single node.

    Worst case would be O(n), average
    O(log n).
"""


def invertTree(root):
    if root is None:
        return root
    # base case
    temp = root.left
    root.left = invertTree(root.right)
    root.right = invertTree(temp)
    return root


if __name__ == '__main__':
    tree = Tree([4, 2, 7, 1, 3, 6, 9])
    out = invertTree(tree.head)
    out_Tree = Tree([])
    out_Tree.head = out
    out_Tree.print_tree()
Beispiel #11
0
def construct_full_tree(board, pl):
    '''
        + The main part starts here.
        + this function constructs nodes, a node represents a state.
        + state is the board after certain moves.
        + this function returns only the min_max Tree with pruning if asked for.
        + The algorithm keeps creating nodes as long as the last depth (level) nodes
            didn't exceed the time when they were being created.
        + Inputs: board and a player
        + Outputs: tree
    '''    
    print ("THINKING...This might take awhile.")
    #Crete the Root Node, add it to the tree and the Q
    player = deepcopy(pl)       #just to make sure, no shallow copy occurs
    root = Node(board,player,evaluate(board))   #the root
    tree = Tree(root)
    tree.inc_depth()
    switch = "switch"
    Q = deque()                 #Q for adding nodes to be spanned later
    Q.append(root)              #append the root of course
    Q.append(switch)            #switch: new generation is comming. ie. new level, new depth.
    new_gen = True              #for tree construction
    this_is_root = True
    start_time, end_time = None, None
    
    while len(Q) > 1:
        
        root = Q.popleft()
        if root == "switch":
            #swap players
            player = 1 if player == -1 else -1
            Q.append(switch)
            end_time = time.time()

            if start_time == None:
                tree.inc_depth()
            elif end_time - start_time < TUNE:
                if VERBOSE: print (f'Tree depth till now: {tree.depth}\t\tTime: {end_time-start_time}')
                tree.inc_depth()
                #after each level produced, prune if you want to.
                if PRUNE: tree.prune()
                if VERBOSE_DEEP: tree.print_tree()
            else:
                print (f"Time Exceeded at depth: {tree.depth}\t\tTime: {end_time-start_time}")

                return tree
            start_time = time.time()
            new_gen = True
            #this will never happen, unless you have a SUPER computer and N is like 1e4
            if tree.depth == DEPTH:
                break
            continue
        
        if root.pruned:
            if VERBOSE_DEEP: print ("Can't Go Down there, it's pruned")
            continue

        #Get the possible moves from this Node
        possible_moves = where_can_i_move_next(root.board, player)
        
        #No moves from here
        if len(possible_moves) == 0:
            #cost will be massive, cuz this is a WIN
            new_cost = MAX_POS if player == 1 else MAX_NEG
            root.update_cost(new_cost)

        for pos in possible_moves:
            #for each possible move create and append a node
            node = Node (pos[3], player, pos[2])
            tree.append_node(node, root, new_gen)
            new_gen = False
            player_swap = 1 if player == -1 else -1
            score = how_many (pos[3],player_swap)
            if score == 0:
                new_cost = MAX_POS if player == 1 else MAX_NEG
                node.update_cost(new_cost)
            if len(possible_moves) == 1 and this_is_root:
                Q.append(node)
                return tree
            else:
                Q.append(node)
        this_is_root = False

    return tree
Beispiel #12
0
from tree import Tree

if __name__ == "__main__" :
    t = Tree()

    # Rotina de visuais rapidos

    # Caso 1: Inserção
    texto = "testando texto teste testa teste tex t"
    lista_texto = texto.split()
    print("vvv Teste de Inserção vvv")
    for idx, palavra in enumerate(lista_texto):
            print("'" + palavra + "' inserido.")
            t.insert(palavra, idx)
    print("^^^ Teste de Inserção ^^^")
    t.print_tree()
    print("size: " + str(t.size))
    print("^^^ Resultado (Inserção) ^^^")

    # Caso 2: Busca
    print("vvv Teste de Busca vvv")
    for idx, palavra in enumerate(lista_texto):
            r = t.search(palavra)
            print("busca por: '" + palavra + "'. Resultado: " + str(r) + " Esperado: " + str(idx))
    print("^^^ Teste de Busca ^^^")

    # Caso 3: Remoção
    print("vvv Teste de Remoção - Meio vvv")
    print("removendo 't'")
    t.remove("t")
    print("removendo 'testa'")
Beispiel #13
0
class DicomSR(object):
    def __init__(self, report_type="", id_ontology=-1):
        self.report_type = report_type
        self.id_ontology = id_ontology
        self.report = Tree()

    def imprime(self):
        """ Pretty print of a report """
        print u"\n ------ {0} ---------- \n".format(self.report_type)
        self.report.print_tree(0)

    def add_node(self, node, parent):
        self.report.add_node(node, parent)

    def get_ontology(self):
        """ Return current report ontology """
        return self.id_ontology

    def get_flat_data(self):
        flat = {}
        self.report.get_flat_tree(flat)
        return flat

    def get_root(self):
        return self.report.value

    def get_data_from_report(self,
                             template_type,
                             languages=None,
                             position=None,
                             cardinality=None):
        """ Return data from the report in a dictionary

        Keyword arguments:
        languages -- list of languages supported in the  report.
        template_type -- indicates the template type and
                         therefore the information to extract from the report.
        self -- Dict Report with the information extracted from the dicom XML.
        position -- dictionary where it's stored parent and
                    its children position

        """
        substitution_words = {}
        if (template_type in MULTIPLE_PROPERTIES.keys()):
            if (template_type == DICOM_LEVEL):
                # Get keys for this template
                levels_tag = MULTIPLE_PROPERTIES[DICOM_LEVEL][0]
                attrs_tag = MULTIPLE_PROPERTIES[DICOM_LEVEL][1]
                level_name = MULTIPLE_PROPERTIES[DICOM_LEVEL][3]
                level_num = MULTIPLE_PROPERTIES[DICOM_LEVEL][2]
                code = MULTIPLE_PROPERTIES[DICOM_LEVEL][4]
                meaning = MULTIPLE_PROPERTIES[DICOM_LEVEL][5]
                #Init dictinary will hold the substitution.
                # Keys are language code and values  contains
                # values to fill the template
                for language in languages:
                    substitution_words[language] = {
                        levels_tag: [],
                        attrs_tag: []
                    }
                #Get container's concept and its attributes
                containers = []
                attributes = []
                self.report.get_set_data(containers, attributes)
                for container in containers:
                    ontology = get_ontology_level(
                        ontology_id=self.get_ontology(),
                        tree_level=container.get_level(),
                        languages_tag=language)
                    for language in languages:
                        aux = {}
                        aux[level_num] = container.get_level()
                        aux[level_name] = (unicode(ontology, "utf-8"))
                        aux[code] = container.get_code().lower()
                        aux[meaning] = container.get_meaning()[language]
                        substitution_words[language][levels_tag].\
                            append(aux.copy())
                for attribute in attributes:
                    for language in languages:
                        aux = {}
                        aux[code] = attribute.code.lower()
                        aux[meaning] = attribute.meaning[language]
                        substitution_words[language][attrs_tag].\
                            append(aux.copy())

            elif (template_type == CHILDREN_ARRAYS):
                nodes_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][0]
                parent_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][1]
                children_tag = MULTIPLE_PROPERTIES[CHILDREN_ARRAYS][2]
                # Get a flat version of the report
                # TODO: check if the flat version of the tree is
                # always the same
                flat = {}
                self.report.get_flat_tree(flat)
                #Delete leaf items. They are not needed
                flat = {key: flat[key] for key in flat if flat[key]}
                if languages:
                    for language in languages:
                        substitution_words[language] = {nodes_tag: []}

                    for parent, children in flat.iteritems():
                        for language in languages:
                            aux = {
                                parent_tag: parent.get_code().lower(),
                                children_tag: []
                            }
                            position = 0
                            for child in children:
                                aux[children_tag].append(
                                    child.get_meaning()[language])
                                #print parent.get_schema_code()
                                #print child.get_schema_code(), position
                                position += 1
                            substitution_words[language][nodes_tag].append(aux)
                else:
                    for parent, children in flat.iteritems():
                        p_code = (parent.get_schema().lower() + '_' +
                                  parent.get_code().lower())
                        position[p_code] = {}
                        cardinality[p_code] = {}
                        pos = 0
                        for child in children:
                            position[p_code][pos] = child.get_schema_code()
                            cardinality[p_code][
                                pos] = child.get_max_cardinality()
                            pos += 1

            elif (template_type == CODE_ARRAYS):
                #TODO: Change comment on this template to make it different
                #from CHILDREN_ARRAYS
                nodes_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][0]
                parent_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][1]
                children_tag = MULTIPLE_PROPERTIES[CODE_ARRAYS][2]
                for language in languages:
                    substitution_words[language] = {nodes_tag: []}
                codes = self.report.get_code_containers()
                for code in codes:
                    for language in languages:
                        aux = {parent_tag: code.code.lower(), children_tag: []}
                        for option in code.options:
                            aux[children_tag].append(option.meaning[language])
                        substitution_words[language][nodes_tag].append(aux)

        return substitution_words
Beispiel #14
0
    new_n.left = mergeTrees(
        t1.left if t1 else None,
        t2.left if t2 else None
    )
    # merge right
    new_n.right = mergeTrees(
        t1.right if t1 else None,
        t2.right if t2 else None
    )
    return new_n

# Don't make a new node
#def mergeTrees(t1, t2):
#    if t1 is None:
#        return t2
#    if t2 is None:
#        return t1
#    t1.val += t2.val
#    t1.left = mergeTrees(t1.left, t2.left)
#    t1.right = mergeTrees(t2.right, t2.right)
#    return t1

if __name__ == '__main__':
    tree_1 = Tree([1,3,2,5])
    tree_2 = Tree([2,1,3,None,4,None,7])
    merged = mergeTrees(tree_1.head, tree_2.head)
    merged_tree = Tree([])
    merged_tree.head = merged
    merged_tree.print_tree()
    
Beispiel #15
0
class Parser:
    def __init__(self, first_table, keys, consts, idents, compl):
        self.__lexemes = first_table
        self.__table = [x[0] for x in first_table]
        self.__length_lex = len(self.__table)
        # self.__keys = keys
        self.__keys = dict([(value, key) for key, value in keys.items()])
        self.__consts = consts
        self.__complex = compl
        # self.__idents = idents
        self.__idents = dict([(value, key) for key, value in idents.items()])
        self.__idx = 0
        self.__tree = Tree('<signal-program>', None)

    def error(self, tmp):
        self.__idx = self.__idx
        self.__tree.append_node([
            tmp, self.__lexemes[self.__idx][1], self.__lexemes[self.__idx][2]
        ])
        self.__tree.print_tree()
        print('error ' + tmp)
        print("code %d line %d colume %d" %
              (self.__lexemes[self.__idx][0], self.__lexemes[self.__idx][1],
               self.__lexemes[self.__idx][2]))
        exit()

    def idx_error(self):
        self.__idx += 1
        if self.__idx >= self.__length_lex:
            self.__tree.append_node('EOF')
            self.__tree.print_tree()
            print('error EOF')
            exit()

    def unsigned_integer(self):
        self.__tree.append_node('<unsigned_integer>')
        t_idx = self.__table[self.__idx]
        t_el = self.__consts[t_idx - 1000001]
        if (t_idx > 1000000)\
                and (t_idx < 20000000)\
                and isinstance(t_el, int):
            self.__tree.append_node([
                t_el, self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.idx_error()
            self.__tree.set_parent()
        else:
            self.error('no_unsigned_integer')
        self.__tree.set_parent()

    def fractional_part(self):
        self.__tree.append_node('<fractional-part>')
        if self.__table[self.__idx] == 35:
            self.__tree.append_node('#')
            self.idx_error()
            self.__tree.set_parent()
            if self.__table[self.__idx] in [43, 45]:
                self.__tree.append_node('sign')
                self.__tree.append_node(chr(self.__table[self.__idx]))
                self.idx_error()
                self.__tree.set_parent()
                self.__tree.set_parent()
            self.unsigned_integer()
        self.__tree.set_parent()

    def integer_part(self):
        self.__tree.append_node('<integer-part>')
        self.unsigned_integer()
        self.__tree.set_parent()

    def unsigned_number(self):
        # self.__tree.append_node('<unsigned_number>')
        # self.integer_part()
        # self.fractional_part()
        # self.__tree.set_parent()
        self.__tree.append_node('<unsigned_number>')
        t_idx = self.__table[self.__idx]
        t_el = self.__consts[self.__table[self.__idx] - 1000001]
        if (t_idx > 1000000) \
                and (t_idx < 20000000):
            self.__tree.append_node([
                t_el, self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.idx_error()
            self.__tree.set_parent()
        else:
            self.error('no_unsigned_number')
        self.__tree.set_parent()

    def identifier(self):
        self.__tree.append_node('<identifier>')
        tmp = self.__table[self.__idx]
        if (tmp < 1000000) and (tmp > 1000):
            self.__tree.append_node([
                self.__idents[tmp], self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.idx_error()
            self.__tree.set_parent()
        else:
            self.error('no_identifier')
        self.__tree.set_parent()

    def function_identifier(self):
        self.__tree.append_node('<function-identifier>')
        self.identifier()
        self.__tree.set_parent()

    def procedure_identifier(self):
        self.__tree.append_node('<procedure-identifier>')
        self.identifier()
        self.__tree.set_parent()

    def variable_identifier(self):
        self.__tree.append_node('<variable-identifier>')
        self.identifier()
        self.__tree.set_parent()

    def constant_identifier(self):
        self.__tree.append_node('<constant-identifier>')
        self.identifier()
        self.__tree.set_parent()

    def right_part(self):
        self.__tree.append_node('<right-pat>')
        if self.__table[self.__idx] == 44:
            self.__tree.append_node([
                ',', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.idx_error()
            self.__tree.set_parent()
            self.unsigned_integer()
        elif self.__table[self.__idx] == 417:
            self.__tree.append_node('$EXP')
            self.idx_error()
            self.__tree.set_parent()
            if self.__table[self.__idx] == 40:
                self.__tree.append_node('(')
                self.idx_error()
                self.__tree.set_parent()
            else:
                self.error("no '('")
            self.unsigned_integer()
            if self.__table[self.__idx] == 41:
                self.__tree.append_node(')')
                self.idx_error()
                self.__tree.set_parent()
            else:
                self.error("no ')'")
        self.__tree.set_parent()

    def left_part(self):
        self.__tree.append_node('<left-part>')
        self.__tree.append_node('<unsigned_integer>')
        if (self.__table[self.__idx] > 1000000) and (self.__table[self.__idx] <
                                                     1000000):
            self.__tree.append_node([
                self.__consts[self.__table[self.__idx] - 1000001],
                self.__lexemes[self.__idx][1], self.__lexemes[self.__idx][2]
            ])
            self.idx_error()
            self.__tree.set_parent()
        self.__tree.set_parent()
        self.__tree.set_parent()

    # def complex_number(self):
    #     self.__tree.append_node('<complex-number>')
    #     self.left_part()
    #     self.right_part()
    #     self.__tree.set_parent()

    def unsigned_constant(self):
        self.__tree.append_node('<unsigned-constant>')
        self.unsigned_number()
        self.__tree.set_parent()

    def complex_constant(self):
        self.__tree.append_node('<complex-constant>')
        self.__tree.append_node('<complex-number>')
        # if self.__table[self.__idx] == 39:
        #     self.__tree.append_node('\'')
        #     self.__tree.set_parent()
        #     self.idx_error()
        # else:
        #     self.error('no "\'"')
        # self.complex_number()
        # if self.__table[self.__idx] == 39:
        #     self.__tree.append_node('\'')
        #     self.__tree.set_parent()
        #     self.idx_error()
        # else:
        #     self.error('no "\'"')
        self.__tree.append_node('left-part')
        self.__tree.append_node([
            self.__complex[self.__table[self.__idx] - 20000001][0],
            self.__lexemes[self.__idx][1], self.__lexemes[self.__idx][2]
        ])
        self.__tree.set_parent()
        self.__tree.set_parent()
        self.__tree.append_node('right-part')
        self.__tree.append_node([
            self.__complex[self.__table[self.__idx] - 20000001][1],
            self.__lexemes[self.__idx][1], self.__lexemes[self.__idx][2]
        ])
        self.__tree.set_parent()
        self.__tree.set_parent()
        self.idx_error()
        self.__tree.set_parent()
        self.__tree.set_parent()

    def statement(self):
        self.__tree.append_node('<statement>')
        if self.__table[self.__idx] == 414:
            self.__tree.append_node([
                'LINK', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.variable_identifier()
            if self.__table[self.__idx] == 44:
                self.__tree.append_node([
                    ',', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                self.idx_error()
            else:
                self.error("no ','")
            self.unsigned_integer()
        elif self.__table[self.__idx] == 415:
            self.__tree.append_node([
                'IN', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.unsigned_integer()
        elif self.__table[self.__idx] == 416:
            self.__tree.append_node([
                'OUT', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.unsigned_integer()
        # else:
        #     self.error('no_statement')
        if self.__table[self.__idx] == 59:
            self.__tree.append_node([
                ';', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error("no ';'")
        self.__tree.set_parent()

    def statement_list(self):
        self.__tree.append_node('<statement-list>')
        while self.__table[self.__idx] in [414, 415, 416]:
            self.statement()
        self.__tree.set_parent()

    def identifier_list(self):
        # self.__tree.append_node('identifier-list')
        while self.__table[self.__idx] == 44:
            self.__tree.append_node([
                ',', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.variable_identifier()
        # self.__tree.set_parent()

    def range_(self):
        self.__tree.append_node('<range>')
        self.unsigned_integer()
        if self.__table[self.__idx] == 301:
            self.__tree.append_node([
                '..', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        self.unsigned_integer()
        self.__tree.set_parent()

    def range_list(self):
        while self.__table[self.__idx] == 44:
            self.__tree.append_node([
                ',', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.range_()

    def attribute(self):
        self.__tree.append_node('<attribute>')
        if self.__table[self.__idx] in range(407, 413):
            self.__tree.append_node([
                self.__keys[self.__table[self.__idx]],
                self.__lexemes[self.__idx][1], self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        elif self.__table[self.__idx] == 91:
            self.__tree.append_node([
                '[', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.range_()
            self.range_list()
            if self.__table[self.__idx] == 93:
                self.__tree.append_node([
                    ']', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                self.idx_error()
            else:
                self.error('no "]"')
        else:
            self.error('no_attribute')
        self.__tree.set_parent()

    def attribute_list(self):
        while self.__table[self.__idx] in list(range(407, 412)) + [91]:
            self.attribute()

    def declaration(self):
        self.__tree.append_node('<declaration>')
        self.variable_identifier()
        self.identifier_list()
        if self.__table[self.__idx] == 58:
            self.__tree.append_node([
                ':', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ":"')
        self.attribute()
        self.attribute_list()
        if self.__table[self.__idx] == 59:
            self.__tree.append_node([
                ';', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ";"')
        self.__tree.set_parent()

    def declaration_list(self):
        self.__tree.append_node('<declaration-list>')
        while (self.__table[self.__idx] > 1000) and (self.__table[self.__idx] <
                                                     1000000):
            self.declaration()
        self.__tree.set_parent()

    def parameters_list(self):
        self.__tree.append_node('<parameters-list>')
        if self.__table[self.__idx] == 40:
            self.__tree.append_node([
                '(', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no "("')
        self.declaration_list()
        if self.__table[self.__idx] == 41:
            self.__tree.append_node([
                ')', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ")"')
        self.__tree.set_parent()

    def procedure(self):
        self.__tree.append_node('<procedure>')
        if self.__table[self.__idx] == 402:
            self.__tree.append_node([
                'PROCEDURE', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no_PROCEDURE')
        self.procedure_identifier()
        self.parameters_list()
        if self.__table[self.__idx] == 59:
            self.__tree.append_node([
                ';', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ";"')
        self.__tree.set_parent()

    def procedure_declarations(self):
        self.__tree.append_node('<procedure-declarations>')
        while self.__table[self.__idx] == 402:
            self.procedure()
        self.__tree.set_parent()

    def function_characteristic(self):
        self.__tree.append_node('<function_characteristic>')
        if self.__table[self.__idx] == 92:
            self.__tree.append_node([
                '\\', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no "\\"')
        self.unsigned_integer()
        if self.__table[self.__idx] == 44:
            self.__tree.append_node([
                ',', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ","')
        self.unsigned_integer()
        self.__tree.set_parent()

    def function(self):
        self.__tree.append_node('<function>')
        self.function_identifier()
        if self.__table[self.__idx] == 61:
            self.__tree.append_node([
                '=', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no "="')
        self.unsigned_integer()
        self.function_characteristic()
        if self.__table[self.__idx] == 59:
            self.__tree.append_node([
                ';', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ";"')
        self.__tree.set_parent()

    def function_list(self):
        self.__tree.append_node('<function-list>')
        while (self.__table[self.__idx] > 1000) and (self.__table[self.__idx] <
                                                     100000):
            self.function()
        self.__tree.set_parent()

    def math_function_declarations(self):
        self.__tree.append_node('<math-function-declarations>')
        if self.__table[self.__idx] == 413:
            self.__tree.append_node([
                'DEFFUNC', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.function_list()
        self.__tree.set_parent()

    def variable_declarations(self):
        self.__tree.append_node('<variable-declarations>')
        if self.__table[self.__idx] == 406:
            self.__tree.append_node([
                'VAR', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.declaration_list()
        self.__tree.set_parent()

    def constant(self):
        self.__tree.append_node('<constant>')
        if self.__table[self.__idx] > 20000000:
            self.complex_constant()
        elif self.__table[self.__idx] == 45:
            self.__tree.append_node([
                '-', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.unsigned_constant()
        else:
            self.unsigned_constant()
        self.__tree.set_parent()

    def constant_declaration(self):
        self.__tree.append_node('<constant-declaration>')
        self.constant_identifier()
        if self.__table[self.__idx] == 61:
            self.__tree.append_node([
                '=', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no "="')
        self.constant()
        if self.__table[self.__idx] == 59:
            self.__tree.append_node([
                ';', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no ";"')
        self.__tree.set_parent()

    def constant_declaration_list(self):
        self.__tree.append_node('<constant_declaration_list>')
        while (self.__table[self.__idx] > 1000) and (self.__table[self.__idx] <
                                                     1000000):
            self.constant_declaration()
        self.__tree.set_parent()

    def constant_declarations(self):
        self.__tree.append_node('<constant_declarations>')
        if self.__table[self.__idx] == 405:
            self.__tree.append_node([
                'CONST', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.constant_declaration_list()
        self.__tree.set_parent()

    def declarations(self):
        self.__tree.append_node('<declarations>')
        self.constant_declarations()
        self.variable_declarations()
        self.math_function_declarations()
        self.procedure_declarations()
        self.__tree.set_parent()

    def block(self):
        self.__tree.append_node('<block>')
        self.declarations()
        if self.__table[self.__idx] == 403:
            self.__tree.append_node([
                'BEGIN', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no_BEGIN')
        self.statement_list()
        if self.__table[self.__idx] == 404:
            self.__tree.append_node([
                'END', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
        else:
            self.error('no_END')
        self.__tree.set_parent()

    def program(self):
        self.__tree.append_node('<program>')
        if self.__table[self.__idx] == 401:
            self.__tree.append_node([
                'PROGRAM', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.procedure_identifier()
            if self.__table[self.__idx] == 59:
                self.__tree.append_node([
                    ';', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                self.idx_error()
            else:
                self.error('no ";"')
            self.block()
            if self.__table[self.__idx] == 46:
                self.__tree.append_node([
                    '.', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                # self.idx_error()
            else:
                self.error('no "."')
        elif self.__table[self.__idx] == 402:
            self.__tree.append_node([
                'PROCEDURE', self.__lexemes[self.__idx][1],
                self.__lexemes[self.__idx][2]
            ])
            self.__tree.set_parent()
            self.idx_error()
            self.procedure_identifier()
            self.parameters_list()
            if self.__table[self.__idx] == 59:
                self.__tree.append_node([
                    ';', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                self.idx_error()
            else:
                self.error('no ";"')
            self.block()
            if self.__table[self.__idx] == 59:
                self.__tree.append_node([
                    ';', self.__lexemes[self.__idx][1],
                    self.__lexemes[self.__idx][2]
                ])
                self.__tree.set_parent()
                # self.idx_error()
            else:
                self.error('no ";"')
        else:
            self.error('no_program')
        self.__tree.set_parent()

    def parsing(self):
        self.program()
        self.__tree.print_tree()

    def get_tree(self):
        return self.__tree
from tree import Tree
from tree import Node

myTree = Tree()
#print(myTree.get_root())

n = Node('taste',5)
p = Node('var',6)
q = Node('var',7)
r = Node('var',8)
s = Node('name',9)

myTree.add_node(n,myTree.get_root())
print("Traversing the tree after adding 1 node")
myTree.print_tree(myTree.get_root(),0)

myTree.add_node(p,myTree.search_node(myTree.get_root(),n.feature,n.value))
print("Traversing the tree after adding 2 nodes")
myTree.print_tree(myTree.get_root(),0)
myTree.add_node(q,myTree.search_node(myTree.get_root(),n.feature,n.value))
myTree.add_node(r,myTree.search_node(myTree.get_root(),q.feature,q.value))

print("Traversing the tree after adding 4 nodes")
myTree.print_tree(myTree.get_root(),0)
myTree.add_node(s,myTree.search_node(myTree.get_root(),r.feature,r.value))

"""
n.add_child(p)
n.add_child(q)
n.add_child(r)
r.add_child(s)
Beispiel #17
0
from tree import TreeNode, Tree


def isMatch(s, t):
    if (s is None and t is not None) or (s is not None and t is None):
        return False
    elif s is None and t is None:
        return True
    return s.val == t.val and isMatch(s.left, t.left) \
                          and isMatch(s.right, t.right)


def isSubtree(s, t):
    if isMatch(s, t):
        return True
    if not s:
        return False
    return isSubtree(s.left, t) or isSubtree(s.right, t)


if __name__ == '__main__':
    s_in = [4, 1, 2, 4, None, None, None, 1]
    s = Tree(s_in)

    t_in = [4, 1]
    t = Tree(t_in)

    print(isSubtree(s.head, t.head))
    s.print_tree()