def __init__(self,chars): q = PriorityQueue() counter = itertools.count() # unique sequence count for freq,char in chars: q._put((freq,(next(counter),HuffNode(freq=freq,val=char)))) for _ in range(len(chars)-1): left = q._get() right = q._get() freq = left[0] + right[0] z = HuffNode(freq=freq,lchild=left[1][1],rchild=right[1][1]) z.lchild.prnt = z.rchild.prnt = z q._put((freq,(next(counter),z))) self.root = q._get()[1][1] self.codes_dict = self._codes()
def solution(n, start, end, roads, traps): # 보드 파싱 board = [[inf] * n for _ in range(n)] for road in roads: s, e, c = road if c < board[s - 1][e - 1]: board[s - 1][e - 1] = c # return board # 모든 함정의 경우의 수 2^len(traps)에 대한 cost dict 생성 # 함정 문자열은, 모든 노드 중 밟은 함정노드가 1로 되어있는 문자열 # 이후 함정 dict를 통해 특정노드가 함정인지 아닌지 쉽게 파악가능 # 모든 함정 경우에 대해 보드도 미리 만들어 둔다 cost = {} boards = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n boards[active_traps] = swap_board(board, bin(active_traps)[2:][::-1]) cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # return cost # return boards # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() if current_node == end - 1: return current_cost current_board = boards[current_trap_int] for idx, v in enumerate(current_board[current_node]): if v != inf: next_trap_int = current_trap_int if idx in traps: next_trap_int = current_trap_int ^ (1 << idx) if (cost[current_trap_int][idx] > current_cost + current_board[current_node][idx]): cost[current_trap_int][ idx] = current_cost + current_board[current_node][idx] pq._put((cost[current_trap_int][idx], idx, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
def _get(self): heappop = heapq.heappop while True: item, i = PriorityQueue._get(self) validity = self.values[item[1]] if validity[1] <= 1: del self.values[item[1]] else: validity[1] -= 1 #Reduce the count if i == validity[0]: validity[2] = False return item else: self.size_diff -= 1
def A_star_search(graph, start, goal): """ Given a graph, a start node and a goal node Utilize A* search algorithm by finding the path from start node to the goal node Use early stoping in your code This function returns back a dictionary storing the information of each node and its corresponding parent node Arguments: graph -- A dictionary storing the edge information from one node to a list of other nodes start -- A character indicating the start node goal -- A character indicating the goal node Return: came_from -- a dictionary indicating for each node as the key and value is its parent node """ came_from = {} cost_so_far = {} costso={} came_from[start] = None cost_so_far[start] = 0 costso[start]=0 ### START CODE HERE ### (≈ 15 line of code) sq=PriorityQueue() visited=[] sq._put((0,start)) while sq: parent=sq._get()[1] target = graph.edges[parent] targetcost=graph.edgeWeights[parent] if parent not in visited: visited.append(parent) if parent == goal: return came_from, cost_so_far for i in target: if (i not in cost_so_far) or (cost_so_far[i] > targetcost[target.index(i)] + cost_so_far[parent]): came_from[i]=parent cost_so_far[i]=(targetcost[target.index(i)]+cost_so_far[parent]) sq._put(((cost_so_far[i]+heuristic(graph, start, i)),i)) ### END CODE HERE ### return came_from, cost_so_far
class Dijkstra: def __init__(self,gameboard): self.grid = [[None for x in range(gameboard.height)] for x in range(gameboard.width)] self.run() self.qset = queue() self.pqueue = PriorityQueue() def run(self, gameboard,x,y): print(gameboard.height*gameboard.width) for i in range (gameboard.height): for j in range (gameboard.width): self.grid[i][j] = grid(i,j,999) self.pqueue._put(self.grid[i][j]) self.grid[x][y]=0 while self.pqueue.empty(): lilgrid = self.pqueue._get() pass
def __a_star(self, world, fr, to, ignore_walls): ''' @Joe Returns the path from 'from' to 'to' if the path doesn't exist then it returns the incomplete path (path, True) if complete (path, False) if incomplete ''' start = fr goal = to frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): current = frontier._get() if current == goal: break if ignore_walls: neighbors = self.__surrounding_pairs_s(world, current) # get path w/o walls else: neighbors = self.__list_neighbors(world, current) # get path w walls for next in neighbors: new_cost = cost_so_far[current] + 1 if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost + sqrt(pow((goal[0] - next[0]),2) + pow((goal[1] - next[1]),2)) frontier.put(next, priority) came_from[next] = current path = [] complete = False while to is not None: path = [to] + path if to in came_from and fr == came_from[to]: complete = True if to not in came_from: break to = came_from[to] return (path, complete)
def dijkstra(self, start: Vertex): """Docstring""" dict_distance = {} dict_path = {} priority_queue = PriorityQueue() priority_queue.put((0, start.data)) # Completa los valores iniciales de list_distance y list_path for vertex in self: dict_distance[vertex.data] = None # asegura la convergencia dict_path[vertex.data] = None dict_distance[start.data] = 0 # # Agrega los nodos a un diccionario graph = {} for vertex in self: aux_list = [] for edge in vertex: aux_list.append((edge.weights[0], edge.destiny.data)) graph[vertex.data] = aux_list # # Busca todas las rutas más rápidas entre nodos, tomando como base el nodo origen while not priority_queue.empty(): smaller_point = priority_queue._get() for next_node in graph[smaller_point[1]]: # Recorre el grafo, nodo por nodo if dict_distance[next_node[1]] == None or next_node[0] + dict_distance[smaller_point[1]] < \ dict_distance[next_node[1]]: dict_distance[next_node[1]] = next_node[0] + dict_distance[smaller_point[1]] dict_path[next_node[1]] = smaller_point[1] priority_queue.put(next_node) return dict_path
def solution(n, start, end, roads, traps): # 보드 파싱 board = [[inf] * n for _ in range(n)] for road in roads: s, e, c = road if c < board[s - 1][e - 1]: board[s - 1][e - 1] = c # return board # 모든 함정의 경우의 수 2^len(traps)에 대한 cost dict 생성 # 함정 문자열은, 모든 노드 중 밟은 함정노드가 1로 되어있는 문자열 # 이후 함정 dict를 통해 특정노드가 함정인지 아닌지 쉽게 파악가능 # 모든 함정 경우에 대해 보드도 미리 만들어 둔다 cost = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # return cost # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() current_trap_str = bin(current_trap_int)[2:].zfill(n)[::-1] if current_node == end - 1: return current_cost from_there = [_[current_node] for _ in board] to_here = board[current_node] next_nodes = [ i for i, x in enumerate(zip(from_there, to_here)) if x[0] != inf or x[1] != inf ] for idx in next_nodes: if idx in traps: next_trap_int = current_trap_int ^ (1 << idx) else: next_trap_int = current_trap_int if ((current_trap_str[current_node] == "1" and current_trap_str[idx] == "1") or (current_trap_str[current_node] == "0" and current_trap_str[idx] == "0")): current_edge = board[current_node][idx] else: current_edge = board[idx][current_node] if current_edge != inf: if (cost[current_trap_int][idx] > current_cost + current_edge): cost[current_trap_int][idx] = current_cost + current_edge pq._put((cost[current_trap_int][idx], idx, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
# 输入的第一行为数组,每一个数用空格隔开,第二行为num。 # Output # 输出一个值。 # Sample Input 1 # 3 6 4 3 2 # 2 # Sample Output 1 # 6 from queue import PriorityQueue pq = PriorityQueue() res = 0 nums = input().split() num = int(input()) # for i in nums: # i=int(i) # if(not pq.empty() and pq._get() ) pq.put(1) pq.put(0) pq.put(2) print(pq._get()) print(pq._get())
def _get(self): item = PriorityQueue._get(self) self.values.remove(item[1]) return item
def _get(self): """Remove queue from both PQ and items dictionary""" p, q = PriorityQueue._get(self) del self._prio_levels[p] return p, q
total = len(a) * len(a) print(a) start = time.time() vali = validation(a) if not vali: print("Cannot be solved") else: name = computeString(a) components = connected_components(a) process_space.put( (total - components, Configuration(a, name, 0, components))) processed.add(name) while not process_space.empty(): config = process_space._get() components = connected_components(config[1].matrix) count = count + 1 # print(components) if components == len(a) * len(a): print("Solved!") break boolean = process(config) if boolean: break end = time.time() print("no. of nodes explored : " + str(count)) print("Time taken : " + str(end - start))
def uniform_cost_search(graph, start, goal): """ Given a graph, a start node and a goal node Utilize uniform cost search algorithm by finding the path from start node to the goal node Use early stoping in your code This function returns back a dictionary storing the information of each node and its corresponding parent node Arguments: graph -- A dictionary storing the edge information from one node to a list of other nodes start -- A character indicating the start node goal -- A character indicating the goal node Return: came_from -- a dictionary indicating for each node as the key and value is its parent node """ came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 ### START CODE HERE ### (≈ 15 line of code) if start not in graph.edges: print(" the ", start, "not exist in", graph) return {}, {} elif goal not in graph.edges: print(" the ", goal, "not exist in", graph) return {}, {} else: sq = PriorityQueue() visited = [] sq._put((0, start)) while sq: parent = sq._get()[1] target = graph.edges[parent] targetcost = graph.edgeWeights[parent] if parent not in visited: visited.append(parent) if parent == goal: return came_from, cost_so_far for i in target: if (i not in cost_so_far) or ( cost_so_far[i] > targetcost[target.index(i)] + cost_so_far[parent]): came_from[i] = parent print(came_from) cost_so_far[i] = (targetcost[target.index(i)] + cost_so_far[parent]) sq._put((cost_so_far[i], i)) print(sq.queue) # target = graph.edges[start] # targetcost=graph.edgeWeights[start] # parent = start # while goal not in target: # for item in target: # if (item not in cost_so_far) or (cost_so_far[item]>targetcost[target.index(item)]+cost_so_far[parent]): # came_from[item] = parent # cost_so_far[item]=targetcost[target.index(item)]+cost_so_far[parent] # sq._put((cost_so_far[item], item)) # parent= sq._get()[1] # targetcost=graph.edgeWeights[parent] # target = graph.edges[parent] # came_from[goal] = parent # cost_so_far[goal]=targetcost[target.index(goal)]+cost_so_far[parent] ### END CODE HERE ### return came_from, cost_so_far
from dataclasses import dataclass, field from queue import PriorityQueue @dataclass(order=True) class Person: name: str = field(compare=False) priority: int = 0 greater_than: set = field(default_factory=set, compare=False) def main(): n, m = map(int, input().split()) names = input().split() people = {name: Person(name) for name in names} a = PriorityQueue() a._put(Person("jon", 0)) a._put(Person("jona", 2)) a._put(Person("helgi", 6)) a._put(Person("bardur", 3)) print(a._get().name) print(a._get().name) print(a._get().name) print(a._get().name)
def solution(n, start, end, roads, traps): # 보드 생성 # 역간선을 미리 만들어 둔다 board = {} for road in roads: s, e, c = road if not s - 1 in board: board[s - 1] = {} if not e - 1 in board: board[e - 1] = {} board[s - 1][e - 1] = [c, 1] board[e - 1][s - 1] = [c, -1] # return board # 함정 상태별 최소거리 cost 기록 # 보드도 미리 만들어 둔다 cost = {} boards = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n boards[active_traps] = swap_board(board, bin(active_traps)[2:][::-1]) # return boards cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() if current_node == end - 1: return current_cost current_board = boards[current_trap_int] for k, v in current_board[current_node].items(): if v[1] == 1: next_trap_int = current_trap_int if k in traps: next_trap_int = current_trap_int ^ (1 << k) if (cost[current_trap_int][k] > current_cost + current_board[current_node][k][0]): cost[current_trap_int][ k] = current_cost + current_board[current_node][k][0] pq._put((cost[current_trap_int][k], k, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
def _get(self, heappop=heapq.heappop): _, _, item = PriorityQueue._get(self) return item