def Dijkstra(s): que = PQueue([(0, s)]) d[s] = 0 while not que.isEmpty(): p = que.pop() v = p[1] if d[v] < p[0]: continue for i in xrange(len(G[v])): e = G[v][i] t = e[1] cost = e[2] if d[t] > d[v] + cost: d[t] = d[v] + cost prev[t] = v que.push((d[t], t))
def min_cost_flow(s, t, f): res = 0 for i in xrange(V): h[i] = 0 while f > 0: for i in xrange(V): dist[i] = inf dist[s] = 0 que = PQueue([(0, s)]) while not que.isEmpty(): p = que.pop() v = p[1] if dist[v] < p[0]: continue for i in xrange(len(G[v])): e = G[v][i] to = e[0] cap = e[1] cost = e[2] nxt = dist[v] + cost + h[v] - h[to] if cap > 0 and dist[to] > nxt: dist[to] = nxt prev_v[to] = v prev_e[to] = i que.push((dist[to], to)) if dist[t] == inf: return -1 for v in xrange(V): h[v] += dist[v] d = f v = t while v != s: d = min(d, G[prev_v[v]][prev_e[v]][1]) v = prev_v[v] f -= d res += d * h[t] v = t while v != s: e = G[prev_v[v]][prev_e[v]] G[prev_v[v]][prev_e[v]][1] -= d G[v][e[3]][1] += d v = prev_v[v] return res
def make_tree(sym_table): q = PQueue() for x in sym_table: if x.count > 0: q.push(x) while True: n1 = q.pop() if q.isEmpty(): if n1.code is not None: for x in sym_table: if x.count == 0: return Node(None, 0, n1, x) return n1 n2 = q.pop() q.push(Node(None, n1.count + n2.count, n1, n2))
def main(): # Step 1: get user and get access token from username username = input('Enter username: '******'Playlist name: ') if (name): playlistID = fetchPlaylistID(sp, username, name) pq = PQueue() # Step 3: in a perpetual loop, modify the playlist while (True): command = input('cmd: ') if (command == 'i'): keyword = input('Give keyword: ') result = sp.search(q=keyword, limit=1) trackID = result['tracks']['items'][0]['id'] if (name): sp.user_playlist_add_tracks(username, playlistID, [trackID]) out = open('audio-analysis.py', 'w') pprint.pprint(sp.audio_analysis(trackID), out) elif (command == 's'): sp.shuffle(True) elif (command == 'pa'): sp.pause_playback() elif (command == 'pl'): sp.start_playback() elif (command == 'n'): sp.next_track() elif (command == 'pr'): sp.previous_track() elif (command == 'c'): currentTrack = sp.current_user_playing_track() if (currentTrack != None): print('Currently playing ', currentTrack['item']['name']) elif (command == 'r'): sp.user_playlist_reorder_tracks(username, playlistID, 3, 0) print("Done!") else: print("Can't get token for", username)
def Dijkstra(s): que = PQueue([(0, s)]) dist[s] = 0 while not que.isEmpty(): p = que.pop() v = p[1] d = p[0] if dist2[v] < d: continue for i in xrange(len(G[v])): e = G[v][i] d2 = d + e[2] if dist[e[1]] > d2: tmp = dist[e[1]] dist[e[1]] = d2 d2 = tmp que.push((dist[e[1]], e[1])) if dist2[e[1]] > d2 and dist[e[1]] < d2: dist2[e[1]] = d2 que.push((dist2[e[1]], e[1]))
from pqueue import PQueue import random import sys import uuid Q = PQueue() while 1: inputs = [] for i in range(10): key = random.randint(1, 1000) inputs.append(key) Q.push(key, str(uuid.uuid4())) test = Q._heap[random.randint(0, len(Q._heap) - 1)] Q.push(0, test.value) key, value = Q.pop() if test.value != value: print('Error') print(inputs) print(test.value) sys.exit(1) print('OK')
print("Not allowed by robot " + base_url) else: print("Url already crawled") except Exception: pass result_file.close() if __name__ == '__main__': start_time = time.time() maritime_keyword_list, stopword_list, aircraft_list = preprocessing() seed_urls = [ 'http://en.wikipedia.org/wiki/List_of_maritime_disasters', 'http://en.wikipedia.org/wiki/Sinking_of_the_MV_Sewol', 'https://www.nytimes.com/2019/06/10/world/asia/sewol-ferry-accident.html', 'https://www.bbc.com/news/world-asia-39361944', 'https://www.history.com/news/5-maritime-disasters-you-might-not-know-about' ] frontierManager = PQueue() score = 4 for url in seed_urls: frontierManager.add_task(url, priority=-score) wave[url] = 1 inlinks[url] = [] crawl_web(frontierManager) print("-------------Finished crawling----------------") print("Crawled " + str(len(data_to_be_indexed)) + " docs")
# coding: utf-8 from pqueue import PQueue import sys if __name__ == '__main__': N = 4 L = 25 P = 10 A = [10, 14, 20, 21] B = [10, 5, 2, 4] A.append(L) B.append(0) que = PQueue(order=-1) ans = 0 pos = 0 tank = P for i in range(N): d = A[i] - pos while tank < d: if que.isEmpty(): print -1 sys.exit() tank += que.pop() ans += 1 tank -= d pos = A[i]
from pqueue import PQueue p = PQueue() p.enqueue("HELLO" , 1) p.enqueue("H", 2) p.enqueue("E", 5) p.enqueue("L", 3) p.enqueue("O", 3) p.enqueue("Sample", 9) #6 print(p.size()) #Sample print(p.dequeue()) #E print(p.dequeue()) #4 print(p.size()) #L print(p.dequeue()) #O print(p.dequeue()) #H print(p.dequeue())
# coding: utf-8 from pqueue import PQueue if __name__ == '__main__': N = 3 L = [8, 5, 8] que = PQueue(L) ans = 0 while len(que.buff) > 1: l1 = que.pop() l2 = que.pop() ans += (l1 + l2) que.push(l1 + l2) print ans
"""Implementing pqueue stress test""" from pqueue import PQueue import random import sys import uuid Q = PQueue() while 1: inputs = [] for i in range(100): key = random.randint(0, 1000) inputs.append(key) Q.push(key, str(uuid.uuid4())) keys = [] while not Q.empty(): key, value = Q.pop() keys.append(key) for i in range(1, len(keys)): if keys[i] < keys[i - 1]: print('ERROR') print(inputs) print(keys) sys.exit(1) print('OK') print(keys)
def runAlgorithm(startNode, endNode): # SAMPLE ALGORITHM # define helper methods def nodeWithShortestDistance(frontier): distance = float('inf') shortestId = None for key, val in frontier.iteritems(): if val['distance'] < distance: distance = val['distance'] shortestId = key return gn.nodeCache[shortestId] def getNextNodes(node): for key in gn.wayCache: for inode in gn.wayCache[key]: if gn.nodeCache[inode]['id'] == node['id']: retArr = [] for key2 in gn.wayCache[key]: retArr.append(key2) return retArr # if node['id'] in gn.wayCache: # print("YES ITS IN WAYCACHE") # print(gn.wayCache[node['id']]) # for key,val in gn.wayCache[node['id']].iteritems(): # nextNodes.append(gn.nodeCache[key]) return [] def costBetweenTwoNodes(node1, node2): radlat1 = math.pi * node1['lat']/180 radlat2 = math.pi * node2['lat']/180 radlon1 = math.pi * node1['lon']/180 radlon2 = math.pi * node2['lon']/180 theta = node1['lon'] - node2['lon'] radtheta = math.pi * theta/180 dist = math.sin(radlat1) * math.sin(radlat2) + math.cos(radlat1) * math.cos(radlat2) * math.cos(radtheta) dist = math.acos(dist) dist = dist * 180/math.pi dist = dist * 60 * 1.1515 dist = dist * 1.609344 * 1000 return dist def costFromStart(node): return costBetweenTwoNodes(startNode, node) def costTillGoal(node): return costBetweenTwoNodes(node, endNode) # start the computation! maxSteps = 1000 node = startNode node['prevCost'] = 0 pq = PQueue() alreadyExplored = {} # cost function = costTillNow + costTillGoal fstart = 0 + costTillGoal(node) pq.put(node, fstart) print("Starting computation.") while not pq.isEmpty() and maxSteps > 0: curNode = pq.get() if curNode['id'] in alreadyExplored: maxSteps = maxSteps - 1 continue alreadyExplored[curNode['id']] = True # if goal found if curNode['id'] == endNode['id']: print("Found a path.") latLng = [] while 'previous' in curNode: latLng.append({'nodeLat': curNode['lat'], 'nodeLong': curNode['lon']}) curNode = curNode['previous'] gn.drawLine({'pTime': 10000 - maxSteps*10, 'pathLine': latLng}) break # for each neighbor node nextNodes = getNextNodes(curNode) for i in range(0, len(nextNodes)): nextNode = gn.nodeCache[nextNodes[i]] if nextNode['id'] in alreadyExplored: continue nextNode['previous'] = curNode nextNode['prevCost'] = curNode['prevCost'] + costBetweenTwoNodes(curNode, nextNode) # cost function = costTillNow + costTillGoal fn = nextNode['prevCost'] + costTillGoal(nextNode) pq.put(nextNode, fn) gn.drawCircle({'circleLat': curNode['lat'], 'circleLong': curNode['lon'], 'circleTime': 10000 - maxSteps*10}) maxSteps = maxSteps - 1
from pqueue import PQueue pq = PQueue([4, 5, 9, 4, 6, 7, 2, 0, 6, 8]) print(pq) pq.pool() print(pq)