def inicializar(self): contador = 0 while contador < 4: self.celulas = [] for i in range(self.linhas): linha = [] for j in range(self.colunas): celula = Celula() celula.y = i celula.x = j celula.inicio = False celula.fim = False celula.visitada = False linha.append(celula) self.celulas.append(linha) self.celulas[0][0].inicio = True self.celulas[-1][-1].fim = True contador = contador + 1 self.pilha = Stack() self._qtdVisitadas = 0 self.criar() if (not self.fechada(self.celulas[1][1])) and \ (not self.fechada(self.celulas[-2][-2])): break if contador < 4: self.valido = True
def __init__(self, board): self.board = board self.moves = KnightsTourMoves() self.tour_steps_stack = Stack(max_size=board.size_horizontal * board.size_vertical) self.tries = 0 self.start_time = time.time()
def __init__(self): self._pilha = Stack() self._corrente = None self._caminho = [] # Norte, Sul, Leste, Oeste: self._incrementos = [[0, -1], [0, 1], [1, 0], [-1, 0]] self._visitadas = [] self._plabirinto = None
class Solver: def __init__(self): self._pilha = Stack() self._corrente = None self._caminho = [] # Norte, Sul, Leste, Oeste: self._incrementos = [[0, -1], [0, 1], [1, 0], [-1, 0]] self._visitadas = [] self._plabirinto = None def solve(self, labirinto): for xLin in range(labirinto.linhas): colunas = [] for xCol in range(labirinto.colunas): colunas.append(False) self._visitadas.append(colunas) self._plabirinto = labirinto self._corrente = labirinto.celulas[0][0] self._pilha.push(self._corrente) self.procurar() while (self._pilha.top): self._caminho.append(self._pilha.pop()) labirinto.caminho = self._caminho def procurar(self): buffer = None while (self._pilha.top): self._visitadas[self._corrente.y][self._corrente.x] = True if self._corrente.fim: return proxima = None for parede in range(4): if not self._corrente.paredes[parede]: if parede == constantes.NORTE and self._corrente.y == 0: continue coluna = self._corrente.x + self._incrementos[parede][0] linha = self._corrente.y + self._incrementos[parede][1] if coluna >= self._plabirinto.colunas or \ linha >= self._plabirinto.linhas: continue if self._visitadas[linha][coluna]: continue proxima = self._plabirinto.celulas[linha][coluna] if buffer: self._pilha.push(buffer) buffer = None self._pilha.push(proxima) self._corrente = proxima break if not proxima: self._corrente = self._pilha.pop() buffer = self._corrente
def infix_to_suffix(exp): Tree.output = [] theStack = Stack() if not exp: return [] infix = exp.split(" ") length = len(infix) for j in range(length): item = infix[j] flag = { '+': 1, '-': 1, 'x': 2, '÷': 2, '(': 3, ')': 4 }.get(item, 5) if flag == 1: Tree.get_oper(item, 1, theStack) elif flag == 2: Tree.get_oper(item, 2, theStack) elif flag == 3: theStack.push(item) elif flag == 4: Tree.got_paren(theStack) elif flag == 5: Tree.output.append(item) while not theStack.is_empty(): Tree.output.append(theStack.pop()) return Tree.output
def __init__(self, linhas=10, colunas=10): self.linhas = linhas self.colunas = colunas self.celulas = [] self.celulaInicial = None self.celunaFinal = None self.valido = False self._corrente = None self._proxima = None self._qtdTotal = 0 self._qtdVisitadas = 0 self._pilha = Stack() self.inicializar() self.caminho = None
def create_stack(self): screen = True while screen: button, values = self.__stack_view.create() if button == "Cancel": screen = False elif values[0] == "": self.__stack_view.show_message("type_value") elif button == "Create": stack_length = int(values[0]) if stack_length <= 0: self.__stack_view.show_message("number_zero") else: self.__stack_number += 1 stack = Stack(stack_length, self.__stack_number) self.__stacks.append(stack) screen = False self.__stack_view.close()
def answer_two(expression): an = Answer() stack = Stack() result = Fraction(0, 1) # testsuff = "1 1 chu 0 chu 1'1/5 chu 2 +".split(" ") suffix = Tree.infix_to_suffix(expression.get_expression()) str = " ".join(suffix) # print(str) if not suffix: return is_num = None for item in suffix: try: is_num = True result = Answer.get_fraction(item) except Exception: is_num = False if is_num: stack.push(result) else: flag = { '+': 1, '-': 2, 'x': 3, '÷': 4, }.get(item, 5) if flag == 1: a = stack.pop() b = stack.pop() stack.push(a + b) elif flag == 2: a = stack.pop() b = stack.pop() stack.push(b - a) elif flag == 3: a = stack.pop() b = stack.pop() stack.push(a * b) elif flag == 4: a = stack.pop() b = stack.pop() if a == 0: print("you 0") an.wronum = 1 break stack.push(b / a) elif flag == 5: pass expression.set_fraction(stack.peek()) expression.set_value(stack.peek()) return an.wronum
class Labirinto: def __init__(self, linhas=10, colunas=10): self.linhas = linhas self.colunas = colunas self.celulas = [] self.celulaInicial = None self.celunaFinal = None self.valido = False self._corrente = None self._proxima = None self._qtdTotal = 0 self._qtdVisitadas = 0 self._pilha = Stack() self.inicializar() self.caminho = None def inicializar(self): contador = 0 while contador < 4: self.celulas = [] for i in range(self.linhas): linha = [] for j in range(self.colunas): celula = Celula() celula.y = i celula.x = j celula.inicio = False celula.fim = False celula.visitada = False linha.append(celula) self.celulas.append(linha) self.celulas[0][0].inicio = True self.celulas[-1][-1].fim = True contador = contador + 1 self.pilha = Stack() self._qtdVisitadas = 0 self.criar() if (not self.fechada(self.celulas[1][1])) and \ (not self.fechada(self.celulas[-2][-2])): break if contador < 4: self.valido = True def fechada(self, celula): retorno = False if celula.paredes[constantes.NORTE] and \ celula.paredes[constantes.SUL] and \ celula.paredes[constantes.LESTE] and \ celula.paredes[constantes.OESTE]: retorno = True return retorno def criar(self): self._qtdTotal = self.linhas * self.colunas linha = randint(0, self.linhas - 1) coluna = randint(0, self.colunas - 1) self._corrente = self.celulas[linha][coluna] self._corrente.visitada = True self._proxima = self.pegarVizinha(self._corrente) self._proxima.visitada = True self.quebrarParedes(self._corrente, self._proxima) self.pilha.push(self._corrente) self._qtdVisitadas = self._qtdVisitadas - 1 self._corrente = self._proxima self.processaCelula() def processaCelula(self): while True: if self.pilha.top: if self.isDeadEnd(self._corrente) or \ self._corrente.fim or \ self._corrente.inicio: self._proxima = self.pilha.pop() self._corrente = self._proxima else: self._proxima = self.pegarVizinha(self._corrente) self.quebrarParedes(self._corrente, self._proxima) self.pilha.push(self._corrente) self._proxima.visitada = True self._qtdVisitadas = self._qtdVisitadas + 1 self._corrente = self._proxima else: self.celulas[0][0].paredes[constantes.NORTE] = False self.celulas[-1][-1].paredes[constantes.SUL] = False return def isDeadEnd(self, celula): if celula.y: if not self.celulas[(celula.y - 1)][celula.x].visitada: return False if celula.y < (self.linhas - 1): if not self.celulas[(celula.y + 1)][celula.x].visitada: return False if celula.x: if not self.celulas[celula.y][(celula.x - 1)].visitada: return False if celula.x < (self.colunas - 1): if not self.celulas[celula.y][(celula.x + 1)].visitada: return False return True def quebrarParedes(self, c1, c2): if c1.x > c2.x: c1.paredes[constantes.OESTE] = False c2.paredes[constantes.LESTE] = False return if c1.x < c2.x: c1.paredes[constantes.LESTE] = False c2.paredes[constantes.OESTE] = False return if c1.y > c2.y: c1.paredes[constantes.NORTE] = False c2.paredes[constantes.SUL] = False return if c1.y < c2.y: c1.paredes[constantes.SUL] = False c2.paredes[constantes.NORTE] = False return def pegarVizinha(self, celula): procurar = True cel = None while procurar: vizinha = randint(0, 3) if vizinha == constantes.NORTE: if celula.y > 0: cel = self.celulas[(celula.y - 1)][celula.x] elif vizinha == constantes.SUL: if celula.y < (self.linhas - 1): cel = self.celulas[(celula.y + 1)][celula.x] elif vizinha == constantes.LESTE: if celula.x < (self.colunas - 1): cel = self.celulas[celula.y][(celula.x + 1)] else: if celula.x > 0: cel = self.celulas[celula.y][(celula.x - 1)] if cel and not cel.visitada: procurar = False return cel def __str__(self): linhas = [[' ' for i in range((self.colunas * 3) + 1)] for j in range(self.linhas * 3)] for z in linhas: z[-1] = '\n' for i in range(self.linhas): for j in range(self.colunas): matriz = self._get_celula(self.celulas[i][j]) self._insert(linhas, matriz, i, j) flattened = [y for x in linhas for y in x] return ''.join(flattened) def _get_celula(self, cel): linha1 = [' ', ' ', ' '] linha2 = [' ', ' ', ' '] linha3 = [' ', ' ', ' '] if cel.paredes[constantes.NORTE]: linha1 = ['-', '-', '-'] if cel.paredes[constantes.SUL]: linha3 = ['-', '-', '-'] if cel.paredes[constantes.OESTE]: linha1[0] = '+' if linha1[0] == '-' else '|' linha2[0] = '|' linha3[0] = '+' if linha3[0] == '-' else '|' if cel.paredes[constantes.LESTE]: linha1[2] = '+' if linha1[2] == '-' else '|' linha2[2] = '|' linha3[2] = '+' if linha3[2] == '-' else '|' if self.caminho: if self._in_path(cel.y, cel.x): linha2[1] = colored(' ', attrs=['reverse']) return [linha1, linha2, linha3] def _insert(self, linhas, matriz, i, j): linha = i * 2 coluna = j * 2 for l in range(3): for c in range(3): linhas[linha + l][coluna + c] = matriz[l][c] def _in_path(self, linha, coluna): for celula in self.caminho: if celula.y == linha and celula.x == coluna: return True return False
def construct(post): """构造二叉树""" stack = Stack() # parent = None # right = None # left = None for item in post: if not Tree.is_operator(item): parent = Node(item) stack.push(parent) else: parent = Node(item) right = stack.pop() left = stack.pop() parent.right = right parent.left = left stack.push(parent) parent = stack.peek() stack.pop() return Tree(parent)
class KnightsTour: def __init__(self, board): self.board = board self.moves = KnightsTourMoves() self.tour_steps_stack = Stack(max_size=board.size_horizontal * board.size_vertical) self.tries = 0 self.start_time = time.time() def start(self, position: ChessBoardPosition, on_tour_found, on_tour_not_found): self._log_start(position) self._add_first_node(position, self.tour_steps_stack) self._depth_first_search(self.tour_steps_stack) self._print_result() if self.tour_steps_stack.is_full(): on_tour_found(self.tour_steps_stack.as_list()) else: on_tour_not_found() self.tour_steps_stack.clear() def _add_first_node(self, position, stack): root = position stack.push(root) def _depth_first_search(self, stack): self._log_tries() # proceed top = stack.top() moves = self.moves.find_available_moves(top.h_index, top.v_index, self.board.size_horizontal, self.board.size_vertical, stack) # loop through possible move options from current node, # recurrently checking every each one of them while moves.__len__() > 0: next_node = moves.pop(0) if stack.size() < stack.max_size: stack.push(next_node) self._depth_first_search(stack) # if no more moves in this node, remove it from tour stack, # and go back to check other possible moves from previous node if moves.__len__() == 0 and 1 < stack.size() < stack.max_size: stack.pop() def _print_result(self): print("Knights Tour: ") print("[", end="") for i in range(self.tour_steps_stack.size()): print(self.tour_steps_stack.get(i).to_string(), end="; ") print("]") self._print_tries() def _log_tries(self): self.tries += 1 if self.tries % 150000 == 0: self._print_tries() if self.tries % 1000000 == 0: self._print_result() def _print_tries(self): logging.info("Try no " + str(self.tries) + ", time passed: " + self._solving_time() + ". Stack size is " + str(self.tour_steps_stack.size())) def _solving_time(self) -> str: seconds_passed = time.time() - self.start_time return str(int(seconds_passed)) + " sec" def _log_start(self, position: ChessBoardPosition): h_index = position.h_index v_index = position.v_index logging.info("Finding Knight's Tour in progress, beginning at " + str(h_index) + "," + str(v_index))