本文整理汇总了Python中queue.PriorityQueue.qsize方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.qsize方法的具体用法?Python PriorityQueue.qsize怎么用?Python PriorityQueue.qsize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类queue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.qsize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: astar
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def astar(start, env):
#frontier_inserstions zählt die Operationen, frontier_max_size die größte vorkommende Frontier
frontier_insertions = 1
frontier_max_size = 1
start.cost = 0
frontier = PriorityQueue()
frontier.put((0, start))
while frontier.qsize() != 0 :
node = frontier.get()[1]
#print("Visiting node " + node.name)
#print("\n".join(["".join(node.status() for node in line) for line in env]))
#Frontier erweitern, hierbei nur solche Knoten aufnehmen, die besucht werden dürfen (kein X) und noch nie in der Frontier waren
#(ansonsten wäre cost gesetzt)
for neighbour in node.neighbours:
if neighbour.cost is None and not neighbour.blocked:
neighbour.prev = node
neighbour.cost = node.cost + 1
frontier.put(( neighbour.cost + neighbour.h , neighbour))
frontier_insertions += 1
if frontier_max_size < frontier.qsize():
frontier_max_size = frontier.qsize()
if neighbour.goal:
print("Time: {} Memory: {}".format(frontier_insertions, frontier_max_size))
return neighbour
print("Time: {} Memory: {}".format(frontier_insertions, frontier_max_size))
示例2: main
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def main():
global CREATURE_COUNT
if process_targeting_form():
c0 = []
c1 = PriorityQueue()
result_out('[+]\tLoading DB...')
#load in creatures from DB
lc = load_DB()
loaded_creatures = lc.split('\n')
#finish loading
result_out('[+]\tSuccess')
result_out('[+]\tCreating initial batch of creatures...')
cl = create_creatures(CREATURE_COUNT, GENOME_LENGTH, tools)
generation = 0
for i in cl:
c1.put((100, i))
for i in loaded_creatures:
c1.put((50, Creature(0, i)))
for ii in range(0, GENE_POOL_INFLUENCE-1):
c1.put((50, Creature(0, mutate(i))))
result_out('[+]\tSuccess')
result_out('[+]\tPre-breeding in loaded creatures with the population for great success')
while not c1.empty():
c = c1.get()[1]
c0.append(c)
c1 = breed_it(c0)
c1 = c0
result_out('[+]\tSuccess')
exploit_found = 0
while exploit_found == 0 and c1.qsize() > 0::
generation += 1
CREATURE_COUNT = c1.qsize()
result_out('[>]\tRunning with creature_count %d,\tgeneration %d' % (CREATURE_COUNT, generation))
c2 = PriorityQueue(0)
cached_c = 0
total_c = 0
while not c1.empty():
c = c1.get()[1]
total_c += 1
if c.modified == 0:
cached_c += 1
if fitnessfunction(c) == 1:
exploit_found = 1
break
c2.put((c.score, c))
result_out('[i]\tEfficiency %s, cached[%d], total[%d]' % (str((total_c-cached_c) * 1.0 / total_c),cached_c,total_c))
c3 = cull_it(c2)
c4 = []
while not c3.empty():
c = c3.get()[1]
c4.append(c)
c1 = breed_it(c4)
if exploit_found > 0:
result_out('[i]\tExploit found in %d seconds with %d requests' % (abs(int(start_time - time.time())), REQ_TOTAL))
else:
result_out('No exploits found')
示例3: huffman
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def huffman(string):
count = Counter()
q = PriorityQueue()
for letter in string:
count[letter] += 1
string_counted = [[weight, [value, '']] for value, weight in count.items()]
for item in string_counted:
q.put([item[0], item[1]])
while q.qsize() > 1:
left = q.get()
right = q.get()
for x in left[1:]:
x[1] = '0' + x[1]
for x in right[1:]:
x[1] = '1' + x[1]
q.put([left[0] + right[0]] + left[1:] + right[1:])
tree = q.get()
tree = tree[1:]
code = dict()
for pair in tree:
code[pair[0]] = pair[1]
return code
示例4: create_tree
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def create_tree(to_comprime_text):
separated_chars = Counter(to_comprime_text)
nodes = {}
for char in separated_chars:
nodes[char] = Node(separated_chars[char], char)
q = PriorityQueue()
for node in nodes:
q.put((nodes[node].get_node_value(), node))
while q.qsize() > 1:
left = q.get()
right = q.get()
nodes[left[1]].set_binary_node_value(0)
nodes[right[1]].set_binary_node_value(1)
node_representation = nodes[left[1]].get_node_representation() + nodes[right[1]].get_node_representation()
node_value = nodes[left[1]].get_node_value() + nodes[right[1]].get_node_value()
nodes[node_representation] = Node(node_value, node_representation)
nodes[node_representation].set_left_node(nodes[left[1]])
nodes[node_representation].set_right_node(nodes[right[1]])
nodes[left[1]].set_back_node(nodes[node_representation])
nodes[right[1]].set_back_node(nodes[node_representation])
q.put((nodes[node_representation].get_node_value(), node_representation))
return nodes
示例5: solve_q1
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def solve_q1(text):
from queue import PriorityQueue
freq = dict()
for i in text:
if i not in freq:
freq[i] = 0
freq[i] += 1
q = PriorityQueue()
for i in freq:
n = HuffmanNode()
n.f = freq[i]
n.c = i
q.put(n)
while q.qsize() > 1:
a = q.get()
b = q.get()
c = HuffmanNode()
c.f = a.f + b.f
c.l = a
c.r = b
q.put(c)
root = q.get()
ret = 0
for i in freq:
ret += freq[i] * root.get(i)
print(ret)
示例6: dijkstra
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def dijkstra(graph, src, dest):
"""Find shortest path from src to dest
graph:
dict[list[(int, int)]]: {node: [adj_node1, adj_node2,...]}
src (int):
dest (int):
"""
to_process = PriorityQueue()
# Start with the source and zero cost
to_process.put((0, src))
# Now as you process nodes one at a time from the queue
# At the end of processing, you will mark their final weight
final_costs = {}
while to_process.qsize() > 0:
cur_cost, cur_node = to_process.get()
if cur_node in final_costs:
continue
# Send runners! all adjacent nodes get queued with the next cost
# Note: this may be worse than a cost they have while already queued,
# or it may be lower (in which case they'll jump the line
for weight_cur_next, next_node in graph[cur_node]:
to_process.put((cur_cost + weight_cur_next, next_node))
final_costs[cur_node] = cur_cost
return final_costs
示例7: solve
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def solve(initial_state, magic_number, target_position):
q = PriorityQueue()
q.put(initial_state)
labyrinth = {}
visited_less_than_50 = set()
def priority_fcn(s, x, y):
return -(abs(s.x - x) + abs(s.y - y))
def is_wall(x, y):
return bool(sum(map(int, bin(
x * x + 3 * x + 2 * x * y + y + y * y + magic_number)[2:])) % 2)
while q.qsize() > 0:
state = q.get()
if len(state.history) <= 50:
visited_less_than_50.add((state.x, state.y))
if state.x == target_position[0] and state.y == target_position[1]:
break
else:
history = [(state.x, state.y), ] + state.history
for x, y in zip([-1, 1, 0, 0], [0, 0, -1, 1]):
new_x, new_y = state.x + x, state.y + y
# Check if outside labyrinth.
if new_x < 0 or new_y < 0:
continue
# Check if already visited.
x_group = labyrinth.setdefault(new_x, {})
if new_y in x_group:
continue
else:
# Check if wall.
x_group[new_y] = is_wall(new_x, new_y)
if x_group[new_y]:
continue
q.put(path(priority=priority_fcn(state, new_x, new_y),
x=new_x, y=new_y, history=history))
# Print map
columns = []
N = max([max(labyrinth[k].keys()) + 1 for k in range(max(labyrinth.keys()) + 1)])
for k in sorted(labyrinth.keys()):
columns.append([' ' for x in range(N)])
for kk, value in sorted(labyrinth[k].items(), key=lambda x: x[0]):
columns[-1][kk] = '#' if value else '.'
if (k, kk) in state.history:
columns[-1][kk] = 'O'
columns[target_position[0]][target_position[1]] = 'X'
rows = list(map(list, zip(*columns)))
print(" {0}".format('0123456789' * (N // 10))[:len(rows[0]) + 3])
for i, row in enumerate(rows):
print("{0:02d} {1}".format(i, "".join(row)))
return state, visited_less_than_50
示例8: huffTree
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def huffTree(freqs):
p = PriorityQueue()
for i, fr in enumerate(freqs):
if fr:
# print(i, fr)
p.put((fr, HuffNode(info=i)))
while p.qsize() > 1:
l, r = p.get(), p.get()
n = HuffNode(left=l[1], right=r[1])
p.put((l[0]+r[0], n))
return p.get()[1]
示例9: A_star
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def A_star (start, target, grid, grid_size):
states = {}
next_state = PriorityQueue()
current = [heuristic(start, target), 0, start]
next_state.put(current)
states[tuple(start)] = [current[0],[-1,-1]]
found = False
while not found and next_state.qsize() > 0:
current = next_state.get()
coords = current[2]
if (states[tuple(coords)][0] != current[0]):
continue
if (coords[0] != target[0]) or (coords[1] != target[1]):
keys = states.keys()
temp_states = expand(current, target, grid, grid_size)
for state in temp_states:
if tuple(state[2]) not in keys:
next_state.put(state)
states[tuple(state[2])] = [state[0], coords]
elif states[tuple(state[2])][0] > state[0]:
next_state.put(state)
states[tuple(state[2])] = [state[0], coords]
else:
found = True
if not found and next_state.qsize() == 0:
return [[-1, -1], len(states.keys())]
####creates the list of moves for the optimal path
moves = []
parent = current[2]
while states[tuple(parent)][1] != [-1,-1]:
moves.append(parent)
parent = states[tuple(parent)][1]
#print(moves)
####returns the last element (1st move)
return [moves[len(moves)-1], len(states.keys())]
示例10: buildHuffmanTree
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def buildHuffmanTree(frequencies):
'''(PriorityQueue) -> Node
Return the root of the Huffman tree constructed using the
frequencies stored in pq.
'''
p = PriorityQueue()
for key,value in leafNodes(frequencies):
p.put((key,value))
while p.qsize() > 1:
l, r = p.get(), p.get()
node = buildBranch(l[0], r[0])
p.put((node, l[1]+r[1]))
return p.get()[0]
示例11: a_star
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def a_star(graph, src, dest, idx_lookup):
"""Find shortest path from src to dest with heuristics
graph:
dict[list[(int, int)]]: {node: [adj_node1, adj_node2,...]}
src (int):
dest (int):
"""
dest_idx = idx_lookup[dest]
def heuristic(test_idx, lnorm=np.inf):
if lnorm == 1:
return sum((abs(test_idx[0] - dest_idx[0]), abs(test_idx[1] - dest_idx[1])))
elif lnorm == 2:
return np.sqrt((test_idx[0] - dest_idx[0])**2 + (test_idx[1] - dest_idx[1])**2)
else:
# L-inf norm (chessboard distance) to the destination
return max((abs(test_idx[0] - dest_idx[0]), abs(test_idx[1] - dest_idx[1])))
to_process = PriorityQueue()
to_process.put((0, 0, src))
final_costs = {}
while to_process.qsize() > 0:
# print(list(to_process.queue))
cur_heur_cost, cur_cost, cur_node = to_process.get()
if cur_node in final_costs:
continue
# import ipdb
# ipdb.set_trace()
for weight_cur_next, next_node in graph[cur_node]:
test_idx = idx_lookup[next_node]
heur_cost = heuristic(test_idx)
to_process.put((
heur_cost + cur_cost + weight_cur_next,
cur_cost + weight_cur_next,
next_node,
))
final_costs[cur_node] = cur_cost
return final_costs
示例12: prim
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def prim(nodes, edges):
global best_result
node_a = 0
connected_set = {node_a}
used_edges = []
edges_to_add = PriorityQueue()
for edge in edges[node_a]:
if (datetime.now() - start > timedelta(seconds=8)):
if best_result is None:
best_result = top_nominator/top_denominator, top_nominator, top_denominator
print_results(best_result)
edges_to_add.put(edge)
top_nominator = 0
top_denominator = 0
while edges_to_add.qsize() > 0:
if (datetime.now() - start > timedelta(seconds=8)):
if best_result is None:
best_result = top_nominator/top_denominator, top_nominator, top_denominator
print_results(best_result)
min_edge = edges_to_add.get()
if min_edge.node_a not in connected_set:
connected_set.add(min_edge.node_a)
for edge in edges[min_edge.node_a]:
if edge.node_a not in connected_set or edge.node_b not in connected_set:
edges_to_add.put(edge)
used_edges.append(min_edge)
top_nominator += min_edge.a
top_denominator += min_edge.b
elif min_edge.node_b not in connected_set:
connected_set.add(min_edge.node_b)
for edge in edges[min_edge.node_b]:
if edge.node_a not in connected_set or edge.node_b not in connected_set:
edges_to_add.put(edge)
used_edges.append(min_edge)
top_nominator += min_edge.a
top_denominator += min_edge.b
return top_nominator/top_denominator, top_nominator, top_denominator
示例13: prims_weight
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def prims_weight(graph, S):
"""
Runs Prim's algorithm on the graph and returns the weight of the MST.
"""
weight = 0
queue = PriorityQueue()
queue.put((0, S))
visited = [False] * len(graph.nodes)
while queue.qsize() > 0:
(cost, node) = queue.get()
if visited[node]:
continue
visited[node] = True # Mark node as visited
weight += cost # Increment MST weight
for neighbor in graph.nodes[node]: # Enqueue neighbors
if visited[neighbor]:
continue
cost = graph.nodes[node][neighbor]
queue.put((cost, neighbor))
return weight
示例14: shortestPath
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def shortestPath(startY, matrix):
shortestSum = 10**10
pq = PriorityQueue()
curNode = matrix[startY][0]
curNode.tentDist = curNode.edgeCost
for row in matrix:
for node in row:
pq.put(node)
while pq.qsize() > 0:
curNode = pq.get()
if curNode.row > 0:
scanNode(curNode, curNode.row - 1, curNode.col, matrix)
if curNode.row < len(matrix) - 1:
scanNode(curNode, curNode.row + 1, curNode.col, matrix)
if curNode.col < len(matrix) - 1:
scanNode(curNode, curNode.row, curNode.col + 1, matrix)
for i in range(len(matrix)):
if matrix[i][len(matrix) - 1].tentDist < shortestSum:
shortestSum = matrix[i][len(matrix) - 1].tentDist
return shortestSum
示例15: from_frequencies
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import qsize [as 别名]
def from_frequencies(self, frequencies):
forest = PriorityQueue()
# create a new tree for each symbol and add it to the forest
for key in range(256):
frequency = frequencies[key]
tree = HuffmanTree(symbol=key, probability=frequency)
forest.put(tree)
# join the two lowest probability trees together until the forest is combined
while forest.qsize() > 1:
tree1 = forest.get()
tree2 = forest.get()
combined = HuffmanTree(left=tree1, right=tree2, probability=tree1.probability + tree2.probability)
forest.put(combined)
# copy combined tree
tree = forest.get()
self.left = tree.left
self.right = tree.right
self.probability = tree.probability