Пример #1
0
def reconstruct_path(came_from: dict, current: Configuration) -> Stack:
    path = Stack()
    while current is not None:
        path.push(current)
        current = came_from[current]

    return path
Пример #2
0
    def undraw(self):
        tmp_liquids = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            liquid.undraw()
            tmp_liquids.push(liquid)

        self.liquids = tmp_liquids.reverse()
Пример #3
0
 def initiate_stack(self):
     self.__stack = Stack()
     self.append_log("\n---------------Analisador Sintático--------------")
     self.append_log("\n------LOG DE OPERAÇÕES:")
     self.append_log("Empilhar $")
     self.__stack.push('$')
     self.append_log("Empilhar Não-Terminal Inicial \n")
     self.__stack.push('<PROGRAMA>')
Пример #4
0
 def __init__(self, intermediate, var_list, lgc):
     self.__intermediate_code = intermediate
     self.__var_list = var_list
     self.__final_code = []
     self.__log_final_code = []
     self.__stack = Stack()
     self.__label_num = -1
     self.__string_num = -1
     self.__lgc = lgc
Пример #5
0
    def __str__(self) -> str:
        tmp = Stack()
        result = ""
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            result += liquid.getColor() + " -> "
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return result
Пример #6
0
 def __init__(self, name, sx, sy, width, height, height_per_volume,
              liquid_capacity) -> None:
     self.name = name
     self.sx = sx
     self.sy = sy
     self.width = width
     self.height = height
     self.height_per_volume = height_per_volume
     self.capacity = liquid_capacity
     self.liquids = Stack()
     self.colors = {}
Пример #7
0
    def getNumAlternating(self):
        alt = 0
        tmp = Stack()
        prev_color = None
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            color = liquid.getColor()
            if not color == prev_color and prev_color is not None:
                alt += 1
            prev_color = color
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return alt
Пример #8
0
    def cal_dir(self, file_dir, cal_files):
        count = 0
        dir_stack = Stack()
        """
        广度优先遍历文件列表
        """
        if os.path.isdir(file_dir):
            dir_stack.push(file_dir)
            while dir_stack.length() > 0:
                curr_dir = dir_stack.pop()
                for name in os.listdir(curr_dir):
                    if name in conf.PASS_FILE_DIR:
                        continue
                    filepath = os.path.join(curr_dir, name)
                    if os.path.isdir(filepath):
                        dir_stack.push(filepath)
                    else:
                        fileName, fileExtension = os.path.splitext(name)
                        if fileExtension in cal_files:
                            count += self.calculate(filepath)
        else:
            fileName, fileExtension = os.path.splitext(file_dir)
            if fileExtension in cal_files:
                count += self.calculate(file_dir)

        return count
Пример #9
0
    def getNumGroups(self):
        groups = [0]
        g_idx = 0
        tmp = Stack()
        prev_color = None
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            color = liquid.getColor()
            if not color == prev_color and prev_color is not None:
                groups.append(0)
                g_idx += 1

            groups[g_idx] += 1
            prev_color = color
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return len([x for x in groups if x > 0])
Пример #10
0
    def draw(self, win: GraphWin):

        Text(Point(self.sx + (self.width // 2), self.sy + (self.width // 2)),
             self.name).draw(win)

        Line(Point(self.sx, self.sy), Point(self.sx,
                                            self.sy - self.height)).draw(win)
        Line(Point(self.sx + self.width, self.sy),
             Point(self.sx + self.width, self.sy - self.height)).draw(win)
        Line(Point(self.sx, self.sy - self.height),
             Point(self.sx + self.width, self.sy - self.height)).draw(win)

        tmp_liquids = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            liquid.draw(win)
            tmp_liquids.push(liquid)

        self.liquids = tmp_liquids.reverse()
Пример #11
0
    def cal_dir_pro(self, file_dir, cal_files, project_common):
        common_count = 0
        busi_count = 0
        dir_stack = Stack()
        """
        广度优先遍历文件列表
        """
        if os.path.isdir(file_dir):
            dir_stack.push(file_dir)
            while dir_stack.length() > 0:
                curr_dir = dir_stack.pop()
                for name in os.listdir(curr_dir):
                    if name in conf.PASS_FILE_DIR:
                        continue
                    filepath = os.path.join(curr_dir, name)
                    if os.path.isdir(filepath):
                        dir_stack.push(filepath)
                    else:
                        fileName, fileExtension = os.path.splitext(name)
                        if fileExtension in cal_files:
                            iscommon = False
                            for common in project_common:
                                if filepath.find(common) != -1:
                                    iscommon = True
                            if iscommon:
                                common_count += self.calculate(filepath)
                            else:
                                busi_count += self.calculate(filepath)
        else:
            fileName, fileExtension = os.path.splitext(file_dir)
            if fileExtension in cal_files:
                iscommon = False
                for common in project_common:
                    if file_dir.find(common) != -1:
                        iscommon = True
                if iscommon:
                    common_count += self.calculate(file_dir)
                else:
                    busi_count += self.calculate(file_dir)

        return (busi_count, common_count)
Пример #12
0
    def copy(self):
        tmp = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            tmp.push(liquid)

        new_tube = Tube(self.name, self.sx, self.sy, self.width, self.height,
                        self.height_per_volume, self.capacity)

        while not tmp.isEmpty():
            liquid: Liquid = tmp.pop()
            new_tube.addLiquid(liquid.getColor())
            self.liquids.push(liquid)

        return new_tube
Пример #13
0
class Tube:
    def __init__(self, name, sx, sy, width, height, height_per_volume,
                 liquid_capacity) -> None:
        self.name = name
        self.sx = sx
        self.sy = sy
        self.width = width
        self.height = height
        self.height_per_volume = height_per_volume
        self.capacity = liquid_capacity
        self.liquids = Stack()
        self.colors = {}

    def draw(self, win: GraphWin):

        Text(Point(self.sx + (self.width // 2), self.sy + (self.width // 2)),
             self.name).draw(win)

        Line(Point(self.sx, self.sy), Point(self.sx,
                                            self.sy - self.height)).draw(win)
        Line(Point(self.sx + self.width, self.sy),
             Point(self.sx + self.width, self.sy - self.height)).draw(win)
        Line(Point(self.sx, self.sy - self.height),
             Point(self.sx + self.width, self.sy - self.height)).draw(win)

        tmp_liquids = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            liquid.draw(win)
            tmp_liquids.push(liquid)

        self.liquids = tmp_liquids.reverse()

    def undraw(self):
        tmp_liquids = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            liquid.undraw()
            tmp_liquids.push(liquid)

        self.liquids = tmp_liquids.reverse()

    def getNumLiquids(self):
        return self.liquids.getSize()

    def getName(self):
        return self.name

    def getTopLiquid(self):
        if self.liquids.isEmpty():
            return None
        return self.liquids.top()

    def isFull(self):
        return self.getNumLiquids() == self.capacity

    def canAddLiquid(self, liquid):
        liquids_match = self.liquids.isEmpty() or self.liquids.top(
        ).isColorMatch(liquid)
        has_room = not self.isFull()
        return liquids_match and has_room

    def addLiquid(self, color):
        sx = self.sx
        sy = self.sy - self.height + \
            self.height_per_volume * (self.getNumLiquids())
        liquid = Liquid(sx, sy, self.width, self.height_per_volume, color)
        self.liquids.push(liquid)

        if color not in self.colors:
            self.colors[color] = 0

        self.colors[color] += 1

    def removeLiquid(self):
        if not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            self.colors[liquid.getColor()] -= 1
            return liquid

    def copy(self):
        tmp = Stack()
        while not self.liquids.isEmpty():
            liquid: Liquid = self.liquids.pop()
            tmp.push(liquid)

        new_tube = Tube(self.name, self.sx, self.sy, self.width, self.height,
                        self.height_per_volume, self.capacity)

        while not tmp.isEmpty():
            liquid: Liquid = tmp.pop()
            new_tube.addLiquid(liquid.getColor())
            self.liquids.push(liquid)

        return new_tube

    def isSorted(self):
        still_has = set(c for c in self.colors if self.colors[c] > 0)
        return len(still_has) == 1

    def getNumUnsorted(self):
        still_has = set(c for c in self.colors if self.colors[c] > 0)
        result = len(still_has)
        return result if result > 0 else 0

    def getNumAlternating(self):
        alt = 0
        tmp = Stack()
        prev_color = None
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            color = liquid.getColor()
            if not color == prev_color and prev_color is not None:
                alt += 1
            prev_color = color
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return alt

    def getNumGroups(self):
        groups = [0]
        g_idx = 0
        tmp = Stack()
        prev_color = None
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            color = liquid.getColor()
            if not color == prev_color and prev_color is not None:
                groups.append(0)
                g_idx += 1

            groups[g_idx] += 1
            prev_color = color
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return len([x for x in groups if x > 0])

    def __str__(self) -> str:
        tmp = Stack()
        result = ""
        while not self.liquids.isEmpty():
            liquid = self.liquids.pop()
            result += liquid.getColor() + " -> "
            tmp.push(liquid)

        self.liquids = tmp.reverse()
        return result
Пример #14
0
class FinalRaspberry:
    def __init__(self, intermediate, var_list, lgc):
        self.__intermediate_code = intermediate
        self.__var_list = var_list
        self.__final_code = []
        self.__log_final_code = []
        self.__stack = Stack()
        self.__label_num = -1
        self.__string_num = -1
        self.__lgc = lgc

    def get_new_string_name(self):
        self.__string_num += 1
        return ''.join(f'string{self.__string_num}')

    def calculate_arith_exp(self, ar_exp):
        self.append_log(
            'Geração do código final Expressão Aritmética (R2 <- Rfinal)')
        if len(ar_exp) == 1:
            elem = ar_exp[0]
            self.get_value(elem)
        else:
            for elem in ar_exp:
                if is_variable(elem) or is_digit(elem):
                    self.get_value(elem)
                    self.append_final_code('PUSH {R2}',
                                           '@(Result) to the stack\n')
                elif elem == '/':
                    self.append_log('Geração do código final DIVISÃO')
                    self.__final_code.append('@DIVISION')
                    self.append_final_code('POP {R1}',
                                           '@Divisor(under bar) from stack')
                    self.append_final_code('POP {R0}',
                                           '@Dividend(above bar) from stack')
                    div_label = self.get_new_label('div')
                    end_div_label = self.get_new_label('end_div')
                    self.append_final_code(f'MOV R2, #0',
                                           '@Reset R2(Quotient) to 0')
                    self.append_final_code(f'{div_label}:\n',
                                           '@Begin of the label(div)')
                    self.append_final_code(
                        f'CMP R0, R1', '@R0 should be >= than R1 to divide')
                    self.append_final_code(f'BLT {end_div_label}',
                                           '@Jump to end_div if R0 < R1')
                    self.append_final_code(f'ADD R2, R2, #1',
                                           '@Increment R2(Quotient/Result)')
                    self.append_final_code(f'SUB R0, R0, R1 ', '@R0 = R0 - R1')
                    self.append_final_code(f'B {div_label}', '@Jump to ')
                    self.append_final_code(f'{end_div_label}:')
                    self.append_final_code('PUSH {R2}',
                                           '@(Quotient/Result) to the stack')
                    self.__final_code.append('@END-DIVISION')
                elif elem == '*':
                    self.append_log('Geração do código final MULTIPLICAÇÃO')
                    self.__final_code.append('@MULT')
                    self.append_final_code('POP {R1}')
                    self.append_final_code('POP {R0}')
                    self.append_final_code(f'MUL R2, R0, R1', '@R2 = R0 * R1')
                    self.append_final_code('PUSH {R2}',
                                           '@(Result) to the stack')
                    self.__final_code.append('@END-MULT')
                elif elem == '-':
                    self.append_log('Geração do código final SUBTRAÇÃO')
                    self.__final_code.append('@SUB')
                    self.append_final_code('POP {R1}')
                    self.append_final_code('POP {R0}')
                    self.append_final_code(f'SUB R2, R0, R1 ', '@R2 = R0 - R1')
                    self.append_final_code('PUSH {R2}',
                                           '@(Result) to the stack')
                    self.__final_code.append('@END-SUB')
                elif elem == '+':
                    self.append_log('Geração do código final ADIÇÃO')
                    self.__final_code.append('@ADD')
                    self.append_final_code('POP {R1}')
                    self.append_final_code('POP {R0}')
                    self.append_final_code(f'ADD R2, R0, R1 ', '@R2 = R0 + R1')
                    self.append_final_code('PUSH {R2}',
                                           '@(Result) to the stack')
                    self.__final_code.append('@END-ADD')
            self.append_final_code('POP {R2}',
                                   '@Result of the acc from stack to R2\n')

    def get_value(self, elem):
        self.append_log(f'Geração para comando de obter valor')
        if is_digit(elem):
            self.append_final_code(f'MOV R2, #{str(elem)}',
                                   '@Move value to the R2')
        elif is_variable(elem):
            self.append_final_code(f'LDR R1,={elem}',
                                   '@Send address to the R1')
            self.append_final_code(f'LDR R2, [R1]',
                                   '@Move value from R2 to var location')

    def append_final_code(self, txt, comment=''):
        self.__final_code.append(f'{txt} {comment}')

    def get_new_label(self, keyword):
        self.__label_num += 1
        new_label = ''.join(f'_{keyword}{self.__label_num}')
        self.append_log(f'Geração de nova label ({new_label})')
        return new_label

    def append_log(self, log):
        self.__log_final_code.append(log)

    def show_log(self):
        if self.__lgc:
            print("\n-----------CÓDIGO FINAL-------------")
            for logline in self.__log_final_code:
                print(logline)

    def get_header(self):
        self.append_log('Montagem do cabeçalho')
        self.append_final_code('.global main')
        self.append_final_code('.func main')
        self.append_final_code('main:')
        self.append_log('Guardou o endereço do LinkRegister')
        self.append_final_code('LDR R1, =backup_lr', '@Address of the var ')
        self.append_final_code('STR LR, [R1] ', '@Store LinkRegister in var ')
        self.__final_code.append('@------BEGIN--------\n')

    def get_bottom(self):
        self.append_log('Montagem do rodapé ')
        self.__final_code.append('@------END--------')
        self.append_log('Pegou o endereço do LinkRegister da var')
        self.append_final_code('LDR LR, =backup_lr', '@Address of the var ')
        self.append_final_code('LDR LR, [LR]')
        self.append_final_code('BX LR', '@Return from the main function')

        self.append_log('Geração da seção .data ')
        self.append_final_code('\n.data', '@ Data section')
        self.append_final_code('.balign 8', '@Bytes allocated to each var')
        self.append_final_code(f'pattern: .asciz \"%d\"', '@Int format')
        self.append_final_code(f'pattern_print: .asciz \"%d\\n\"')
        self.append_final_code(f'backup_lr: .word 0\n')
        self.append_final_code(f'\n.global printf')
        self.append_final_code(f'.global scanf')
        for var in self.__var_list:
            if 'string' not in var:
                self.append_log(f'Geração da variável ({var})')
                self.append_final_code(f'{var}: .word 0')
            else:
                var_name = var.split('"')[0]
                string_value = var.split('"')[1]
                self.append_log(f'Geração da variável ({var_name})')
                self.append_final_code(
                    f'{var_name}: .asciz \"{string_value}\\n\" ')

    def generate_final_code(self):
        self.append_log('\n--LOG: GERAÇÃO CÓDIGO FINAL')
        self.append_log(
            f'Começo da geração de Código Final Assembly (RASPBERRY PI)')
        inter_code = self.__intermediate_code
        l_index = 0
        OP_RE = ['<>', '=', '<', '>']
        BOOL = ['\\', '&']

        self.get_header()

        while l_index < len(inter_code):
            inter_line = inter_code[l_index].split()[0]

            if inter_line == 'leia':
                self.append_log(f'Geração do comando leia ')
                inter_line = inter_code[l_index].split()[1]
                self.append_final_code('LDR R0, =pattern', '@int pattern (%d)')
                self.append_final_code(f'LDR R1, ={inter_line}',
                                       '@Send variable address')
                self.append_final_code(
                    f'BL scanf',
                    ' @Function to receive input from the keyboard\n')
            elif inter_line == 'escreva':
                inter_line = inter_code[l_index].split()[1]
                if is_variable(inter_line):
                    var = inter_code[l_index].split()[1]
                    self.append_log(f'Geração do comando escreva ({var})')
                    # first case, when it's a variable
                    self.append_final_code('LDR R0, =pattern_print',
                                           '@int pattern (%d)')
                    self.append_final_code(f'LDR R1, ={var}',
                                           '@Send variable address')
                    self.append_final_code(f'LDR R1, [R1]',
                                           '@Send variable address')
                    self.append_final_code(
                        f'BL printf',
                        ' @Function to receive input from the keyboard\n')
                else:
                    string_value = inter_code[l_index].split('"')[1]
                    self.append_log(
                        f'Geração do comando escreva ({string_value})')
                    string_var = self.get_new_string_name()
                    self.append_final_code(f'LDR R0, ={string_var}',
                                           '@Send variable address')
                    self.append_final_code(
                        f'BL printf',
                        ' @Function to receive input from the keyboard\n')
                    self.__var_list.append(f'{string_var}\"{string_value}\"')

            elif '=' in inter_code[l_index].split() and inter_code[l_index].split()[0] != 'se'\
                    and inter_code[l_index].split()[0] != 'enquanto':

                var = inter_code[l_index].split()[0]
                ar_exp = inter_code[l_index].split()[2:]
                self.append_log(f'Geração do comando de atribuição ({var})')

                self.calculate_arith_exp(ar_exp)
                self.append_final_code(f'LDR R1, ={var}',
                                       '@Getting var address')
                self.append_final_code(f'STR R2, [R1] ',
                                       '@Store exp result in var\n')

            elif inter_line == 'se':
                self.append_log(f'Geração do comando condicional se')
                se_label = self.get_new_label('se')
                senao_label = self.get_new_label('senao')
                self.__stack.push(senao_label)

                bool_exp = inter_code[l_index]
                bool_exp_list = bool_exp.split()
                operator_pos = [
                    idx for idx, elem in enumerate(bool_exp_list)
                    if elem in OP_RE
                ]

                i = 0
                while i < len(operator_pos):
                    elem = bool_exp_list[operator_pos[i]]

                    previous_var = bool_exp_list[operator_pos[i] - 1]
                    posterior_var = bool_exp_list[operator_pos[i] + 1]
                    self.__final_code.append('@CONDITION')
                    self.get_value(
                        previous_var)  # value of a prev_var, send it to R2
                    self.append_final_code(f'MOV R3, R2 ',
                                           '@Send end result to R3')
                    self.get_value(
                        posterior_var)  # value of the post_var, send it to R2
                    self.append_final_code(
                        f'CMP R3, R2 ',
                        '@Compare R3 and R2, changes flags status')
                    self.__final_code.append('@END-CONDITION')

                    if elem == '<':
                        self.append_final_code(f'BLT {se_label} ',
                                               '@Jumps if R3 < R1')
                        self.append_final_code(
                            f'B {senao_label}',
                            '@Jumps unconditionally (R3 == R1)')
                    elif elem == '>':
                        self.append_final_code(
                            f'BGT {se_label} ',
                            '@Jumps if R3 > R1 (Zero is set)')
                        self.append_final_code(f'B {senao_label}',
                                               '@Jumps unconditionally ')
                    elif elem == '=':
                        self.append_final_code(
                            f'BEQ {se_label} ',
                            '@Jumps if R3 == R1 (Zero is set)')
                        self.append_final_code(
                            f'B {senao_label}',
                            '@Jumps unconditionally (R3 <> R1)')
                    elif elem == '<>':
                        self.append_final_code(
                            f'BNE {se_label} ',
                            '@Jumps if R3 > R1 (Zero is not set)')
                        self.append_final_code(f'B {senao_label}',
                                               '@Jumps unconditionally ')
                    i += 1
                self.append_final_code(f'{se_label}:',
                                       '@add symbol after expr')
            elif inter_line == 'senao':
                self.append_log(f'Geração do comando senao')
                fim_se_label = self.get_new_label("fim_se")
                senao_label = self.__stack.pop()
                self.append_final_code(f'B {fim_se_label}',
                                       '@Jumps unconditionally')
                self.append_final_code(f'{senao_label}:',
                                       '@add symbol after expr')
                self.__stack.push(fim_se_label)
            elif inter_line == 'fim_se':
                self.append_log(f'Geração do comando fim_se')
                fim_label = self.__stack.pop()
                self.append_final_code(f'{fim_label}:')
            elif inter_line == 'enquanto':

                self.append_log(f'Geração do comando enquanto')
                enquanto_label = self.get_new_label('enquanto')
                fim_enquanto_label = self.get_new_label('fim_enquanto')
                self.__stack.push(fim_enquanto_label)
                self.__stack.push(enquanto_label)
                self.append_final_code(f'{enquanto_label}:',
                                       '@Loop label before condition')

                bool_exp = inter_code[l_index]
                bool_exp_list = bool_exp.split()
                operator_pos = [
                    idx for idx, elem in enumerate(bool_exp_list)
                    if elem in OP_RE
                ]

                i = 0
                while i < len(operator_pos):
                    elem = bool_exp_list[operator_pos[i]]

                    previous_var = bool_exp_list[operator_pos[i] - 1]
                    posterior_var = bool_exp_list[operator_pos[i] + 1]
                    self.__final_code.append('@CONDITION')
                    self.get_value(
                        previous_var)  # value of a prev_var, send it to R2
                    self.append_final_code(f'MOV R3, R2 ',
                                           '@Send end result to R3')
                    self.get_value(
                        posterior_var)  # value of the post_var, send it to R2
                    self.append_final_code(
                        f'CMP R3, R2 ',
                        '@Compare R3 and R2, changes flags status')
                    self.__final_code.append('@END-CONDITION')

                    if elem == '<':
                        self.append_final_code(f'BGE {fim_enquanto_label} ',
                                               '@Jumps if R3 >= R1')
                    elif elem == '>':
                        self.append_final_code(f'BLE {fim_enquanto_label} ',
                                               '@Jumps if R3 =< R1')
                    elif elem == '<>':
                        self.append_final_code(f'BEQ {fim_enquanto_label} ',
                                               '@Jumps if R3 == R1')
                    elif elem == '=':
                        self.append_final_code(f'BNE {fim_enquanto_label} ',
                                               '@Jumps if R3 > R1')
                    self.__final_code.append('@EXPRESSIONS')
                    i += 1
            elif inter_line == 'fim_enquanto':
                self.append_log(f'Geração dos comandos para o fim_enquanto')
                self.__final_code.append('@END-EXPRESSIONS')
                enquanto_label = self.__stack.pop()
                fim_enquanto_label = self.__stack.pop()
                self.append_final_code(f'B {enquanto_label}',
                                       '@Jumps unconditionally ')
                self.append_final_code(f'{fim_enquanto_label}:')

            l_index += 1

        self.get_bottom()
        self.show_log()
        return self.__final_code
Пример #15
0
def a_star(start: Configuration, h) -> Stack:

    # e_time = 0
    # c_time = 0
    # d_time = 0
    # h_time = 0
    # num_children = 0

    best_delta_h = 0

    frontier = BucketQueue()

    came_from = {start: None}

    g_score = {}
    g_score[start] = 0

    f_score = {}
    f_score[start] = h(start)

    frontier.enqueue(f_score[start], start)

    while not frontier.isEmpty():
        # ts = time.time()
        current = frontier.removeMin()
        # te = time.time()
        # d_time += te - ts

        if current.isGoal():
            # print("Enqueue total time: {}".format(e_time))
            # print("Dequeue total time: {}".format(d_time))
            # print("Heuristic total time: {}".format(h_time))
            # print("Children total time: {} Children average time: {}".format(
            #     c_time, c_time / num_children))

            print("Best delta-h: {}".format(best_delta_h))

            return reconstruct_path(came_from, current)

        # ts = time.time()
        children = current.getChildren()
        # te = time.time()
        # c_time += te - ts

        # num_children += len(children)

        for child in children:
            current_gscore = g_score[current] + \
                1  # cost to next node is just 1
            if child not in g_score or current_gscore < g_score[child]:
                came_from[child] = current
                g_score[child] = current_gscore

                delta_h = h(current) - h(child)
                if delta_h > best_delta_h:
                    best_delta_h = delta_h

                # ts = time.time()
                f_score[child] = g_score[child] + h(child)
                # te = time.time()
                # h_time += te - ts

                # ts = time.time()
                if not frontier.hasValue(child):
                    frontier.enqueue(f_score[child], child)
                # te = time.time()
                # e_time += te - ts

    return Stack()
Пример #16
0
class SyntaxAnalyser:
    def __init__(self, tokens, ls):
        self.__tokens = tokens
        self.__syntax_table_values = {
            0: 'BeginFun <LISTA_COMANDOS> EndFun',
            1: '<COMANDO> TK_PERIOD <LISTA_COMANDOS>',
            2: '#',
            3: '<INPUT>',
            4: 'grabInput TK_ID <KEY>',
            5: '<KEY>',
            6: 'TK_COMMA TK_ID <INPUT>',
            7: '#',
            8: '<ANT_VAR> TK_ID <DPS_VAR>',
            9: 'TK_ATRIB <EXP>',
            10: '#',
            11: 'funny',
            12: '#',
            13: '<DISPLAY>',
            14: 'showMeTheCode <DISPLAY_F>',
            15: 'TK_ID',
            16: '<STRING>',
            17: 'TK_STRING',
            18: 'if <EXPR_BOOL> then <LISTA_COMANDOS> <ELSE> end',
            19: 'else <LISTA_COMANDOS>',
            20: '#',
            21: 'funLoopWhile <EXPR_BOOL> do <LISTA_COMANDOS> endFunLoop',
            22: '<OPERAN> <EXP_F>',
            23: 'TK_OPEN_P <EXP> TK_CLOSE_P <EXP_F>',
            24: 'TK_OP_AR <EXP>',
            25: '#',
            26: '<OPER>',
            27: '<OPERAN> <BOOL_F>',
            28: 'TK_OP_RE <EXPR_BOOL>',
            29: '<BOOL_TYPE> <EXPR_BOOL>',
            30: 'TK_BOOL',
            31: '<OPER_REL>',
            32: '#',
            33: 'TK_ID',
            34: 'TK_NUM'
        }
        self.__syntax_table = SYNTAX_TABLE
        self.ls = ls
        self.__log_syntax_analyser = []
        self.initiate_stack()
        self.recognise_sentence()
        self.tokens_recognised()
        self.show_log()

    def append_log(self, log):
        self.__log_syntax_analyser.append(log)

    def show_log(self):
        if self.ls:
            for logline in self.__log_syntax_analyser:
                print(logline)

    def initiate_stack(self):
        self.__stack = Stack()
        self.append_log("\n---------------Analisador Sintático--------------")
        self.append_log("\n------LOG DE OPERAÇÕES:")
        self.append_log("Empilhar $")
        self.__stack.push('$')
        self.append_log("Empilhar Não-Terminal Inicial \n")
        self.__stack.push('<PROGRAMA>')

    def tokens_recognised(self):
        self.append_log("Verificar Pilha Vazia")
        self.append_log("Verificar Estado da Lista\n")
        return self.__stack.isEmpty() and not self.__tokens

    def error_verification(self, top_stack, first_elem):
        tk_line = self.__tokens[0].line
        tk_col = self.__tokens[0].col
        lex = self.__tokens[0].lexeme

        if self.__stack.isEmpty() and self.__tokens:
            self.append_log("Verificar Pilha Vazia")
            self.append_log("Verificar Estado da Lista")
            SyntaxError(tk_line, tk_col, lex,
                        'PILHA VAZIA e ainda há elementos na LISTA')
        elif not self.__stack.isEmpty() and len(self.__tokens) == 0:
            self.append_log("Verificar Pilha Vazia")
            self.append_log("Verificar Estado da Lista")
            SyntaxError(tk_line, tk_col, lex,
                        'LISTA VAZIA e ainda há elementos na Pilha')
        else:
            SyntaxError(
                tk_line, tk_col, lex,
                f'Não encontrou um elemento correspondente na tabela - {top_stack}:{first_elem}'
            )

    def consult_table(self, line, col):
        self.append_log("Buscar Indice na Tabela Sintática")
        rules_index = self.__syntax_table[line][col]
        # prodution found
        if rules_index == '':
            self.error_verification(line, col)
        self.append_log("Retornar Produção Encontrada")
        rule = self.__syntax_table_values[rules_index]
        # pop the last element of the stack
        self.append_log("Desempilhar")
        self.__stack.pop()
        # split the whole rule
        rule = rule.split()
        max = len(rule)
        for i in range(max):
            # send element in opposite order to the stack
            rule_to_stack = rule.pop()
            if rule_to_stack == '#':
                continue
            self.append_log(f"Empilhar Produção: {rule_to_stack}\n")
            self.__stack.push(rule_to_stack)

    def recognise_sentence(self):
        index = 0
        try:
            while not self.tokens_recognised():
                self.append_log('Consultar Topo')
                top_stack = self.__stack.peek()
                self.append_log('Consultar Elemento da Lista')
                first_elem = self.__tokens[index].type
                if top_stack == first_elem:
                    self.append_log(f"Desempilhar ({top_stack})")
                    self.__stack.pop()
                    self.append_log(
                        f"Remover Elemento da Lista ({first_elem})\n")
                    self.__tokens.pop(0)  #removing first token
                elif self.__syntax_table[top_stack][first_elem] != None:
                    self.consult_table(top_stack, first_elem)
        except Exception as ex:
            self.error_verification(top_stack, first_elem)