本文整理汇总了Python中queue.PriorityQueue.append方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.append方法的具体用法?Python PriorityQueue.append怎么用?Python PriorityQueue.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类queue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.append方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: heap
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import append [as 别名]
class NPuzzleSolver:
"""
Uses the BFS/DFS/A* algos to solve a given n-puzzle board
"""
initial_state = None
algo = ""
# The frontier in BFS/DFS is a queue/stack and for A*, its a heap (PriorityQueue)
# Frontier set made to test membership in O(1)
frontier = None
frontier_set = set()
# All of the fully explored states in this set
explored = set()
def __init__(self, algo, initial_state=None):
self.initial_state = initial_state
if algo == "bfs" or algo == "dfs":
self.frontier = dq()
self.frontier.append(initial_state)
else:
self.frontier = PriorityQueue()
self.frontier.put(initial_state)
self.frontier_set.add(initial_state)
self.algo = algo
def solve(self):
"""
Attempts to solve an n-puzzle and returns a stats
dict, or None if no solution exists
"""
start_time = time.time()
maxdepth = 0
break_cond = False
while(not break_cond):
if self.algo == "bfs":
# Pop the leftmost element if doing a bfs (Queue)
current_state = self.frontier.popleft()
elif self.algo == "dfs":
# Pop the rightmost element if doing a dfs (Stack)
current_state = self.frontier.pop()
else:
# Get element with highest priority if doing A* (Heap)
current_state = self.frontier.get()
self.frontier_set.remove(current_state)
if (self.isFinalState(current_state)):
soln = self.get_solution_moves(current_state)
end_time = time.time()
stats = {}
stats["nodes_expanded"] = len(self.explored)
stats["search_depth"] = current_state.depth
stats["max_search_depth"] = maxdepth
stats["cost_of_path"] = len(soln)
stats["time"] = end_time - start_time
stats["path"] = soln
return stats
neighbors = current_state.generate_possible_states()
if self.algo == "dfs":
neighbors.reverse()
for neighbor in neighbors:
if neighbor not in self.explored and neighbor not in self.frontier_set:
if self.algo == "bfs" or self.algo == "dfs":
self.frontier.append(neighbor)
else:
self.frontier.put(neighbor)
self.frontier_set.add(neighbor)
if neighbor.depth > maxdepth:
maxdepth = neighbor.depth
self.explored.add(current_state)
if self.algo == "bfs" or self.algo == "dfs":
frontier_sz = len(self.frontier)
else:
frontier_sz = self.frontier.qsize()
logging.debug("Frontier size = " +
str(frontier_sz) +
"; Explored size = " +
str(len(self.explored)))
if self.algo == "bfs" or self.algo == "dfs":
break_cond = len(self.frontier) == 0
else:
break_cond = self.frontier.empty()
logging.error("This is an unsolvable board!")
return None
def get_solution_moves(self, final_state):
"""
Gets the sequence of moves from parent to this state
"""
moves = dq()
current_state = final_state
while current_state is not None:
if current_state.parent_move is not None:
moves.appendleft(current_state.parent_move)
current_state = current_state.parent
res = []
[res.append(move) for move in moves]
return res
#.........这里部分代码省略.........
示例2: Game
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import append [as 别名]
class Game():
def __init__(self, user_id, teams):
'''
phase - np. przed rozpoczeciem, rozpoczeta
players - wszyscy gracze
points - slownik; points[team] = (lista, pozycja)
teams - nazwy druzyn
'''
self.phase = 0
self.players = []
self.points = None
self.teams = teams
self.not_active_bombs = PriorityQueue()
self.active_bombs = deque()
self.exploding_bombs = deque()
self.created_by = user_id
self.id = self.create_id()
def get_phase(self):
return self.phase
def create_id(self):
return randint(0,255)
#before start
def add_player(self, ID, messanger, team=0, bomb_limit=10, bombs_in_inventory=10, bomb_radius=100):
'''
player = add_player (ID, team, limit_bomb)
'''
if self.get_phase() != 0: raise GameError(1)
for p in self.players:
if p.get_ID() == ID:
raise GameError(3,'player exists')
player = Player(ID, messanger,team,None,bomb_limit,bombs_in_inventory,bomb_radius)
self.players.append(player)
return player
def add_team(self, teamname):
if self.get_phase() != 0: raise GameError(1)
if len(self.teams) >= 2: raise GameError(2,'too many teams')
if teamname in self.teams: raise GameError(3,'team exists')
self.teams.append(teamname)
def assign(self, player, teamname):
'''
player = ID czy klasa? - jak trzyma serwer
(jesli ID, to najpierw trzeba znalezc gracza w players, nie uda sie -> error)
'''
print(player)
for p in self.players:
print(p)
if player not in self.players: raise GameError(4,'player does not exist')
if teamname not in self.teams: raise GameError(4,'team does not exist')
player.set_team(teamname)
def load_points(self):
#check if everything else is done
if self.get_phase() != 0: raise GameError(1)
if len(self.teams) != 2: raise GameError(2,'number of teams should be 2: '+str(len(self.teams)))
if len(self.players) < 1: raise GameError(2,'should have more than 5 players: '+str(len(self.players)))
for p in self.players:
if not p.is_ready(): raise GameError(1,'some players not ready')
#all done -> next phase
self.phase = 1
self.players = tuple(self.players)
l1 = get_points('pointsA.csv')
l2 = get_points('pointsB.csv')
self.points = {self.teams[0]: (l1,0), self.teams[1]: (l2,0)}
self.phase = 2
def start(self):
if self.get_phase() != 2: raise GameError(1)
self.phase = 3
self.Exploder(self).start()
#game - bombs
def place_bomb(self, player, position):
if not player.can_place_bomb():
raise GameError(1)
bomb = Bomb(position[0], position[1], player)
self.not_active_bombs.append((time.time()+bomb.time_to_activate, bomb))
player.bombs_in_inventory -= 1
#simple timer for managing bombs
class Exploder(Thread):
def __init__(self,game):
Thread.__init__(self)
self.game = game
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import append [as 别名]
class hClusterer:
""" this clusterer assumes that the first column of the data is a label
not used in the clustering. The other columns contain numeric data"""
def __init__(self, filename):
file = open(filename)
self.data = {}
self.counter = 0
self.queue = PriorityQueue()
lines = file.readlines()
file.close()
header = lines[0].split(',')
self.cols = len(header)
self.data = [[] for i in range(len(header))]
for line in lines[1:]:
cells = line.split(',')
toggle = 0
for cell in range(self.cols):
if toggle == 0:
self.data[cell].append(cells[cell])
toggle = 1
else:
self.data[cell].append(float(cells[cell]))
# now normalize number columns (that is, skip the first column)
for i in range(1, self.cols):
self.data[i] = normalizeColumn(self.data[i])
###
### I have read in the data and normalized the
### columns. Now for each element i in the data, I am going to
### 1. compute the Euclidean Distance from element i to all the
### other elements. This data will be placed in neighbors, which
### is a Python dictionary. Let's say i = 1, and I am computing
### the distance to the neighbor j and let's say j is 2. The
### neighbors dictionary for i will look like
### {2: ((1,2), 1.23), 3: ((1, 3), 2.3)... }
###
### 2. find the closest neighbor
###
### 3. place the element on a priority queue, called simply queue,
### based on the distance to the nearest neighbor (and a counter
### used to break ties.
neighbors={}
closest = {}
closestDistance = {}
for i in range(len(self.data[0])):
neighbors[i]={}
dis = float('inf')
closeneigh=i
for j in range(len(self.data[0])):
if i!=j:
neighbors[i][j]=((i,j),self.distance(i,j))
if neighbors[i][j][1]<dis:
dis=neighbors[i][j][1]
closeneigh=j
currentCluster = [self.data[0][i]]
currentNeigh = self.data[0][j]
neighList = [currentNeigh,dis,(i,j)]
tupleForQueue= (dis,i,[currentCluster,neighList],neighbors[i])
self.queue.append(tupleForQueue)
def merge(dic1,dic2):
dic3 = {}
assert len(dic1)>0
assert len(dic2)>0
for key in dic1.keys():
if key in dic2:
op1 = dic1[key][1]
op2 = dic2[key][1]
print dic1[key][0]
print dic2[key][0]
if op1<op2:
dic3[key]=(dic1[key][0],op1)
else:
dic3[key]=(dic2[key][0],op2)
return dic3
def distance(self, i, j):
sumSquares = 0
for k in range(1, self.cols):
sumSquares += (self.data[k][i] - self.data[k][j])**2
return math.sqrt(sumSquares)
def cluster(self):
# TODO
currentIndex = len(self.queue)
while len(self.queue)>1:
currentIndex+=1
clus1 = self.queue.get()
clus2 = self.queue.get()
print clus1
print clus2
dist1 = clus1[0]
dist2 = clus2[0]
ney1= clus1[1]
ney2= clus2[1]
if dist1<dist2:
#.........这里部分代码省略.........