def prim(G): cost = {} parent = {} u = None P = PriorityQueue() for v in G.vertexes: if u is None: u = v cost[v] = float('inf') P.add(float('inf'), v) parent[v] = None cost[u] = 0 P.change_priority(u, 0) for i in P.Q: print(i) while not P.isEmpty(): print('wtf') v_ele = P.get_min() vertex = v_ele.data print('minimum', v_ele) for u, v, w in G.get_all_vertex(vertex): print(u, v, w) if P.check_ele(v) and cost[v] > cost[u] + w: cost[v] = cost[u] + w parent[v] = u P.change_priority(v, cost[v]) print(cost) print(parent)
def prims(G): cost = {} parent = {} u = None P = PriorityQueue() for v in G.vertexes: if u is None: u = v cost[v] = float('inf') P.add(float('inf'), v) parent[v] = None cost[u] = 0 P.change_priority(u, 0) while not P.isEmpty(): v_ele = P.get_min() vertex = v_ele.data for u, v, w in G.get_all_vertex(vertex): if P.check_ele(v) and cost[v] > cost[u] + w: cost[v] = cost[u] + w parent[v] = u P.change_priority(v, cost[v])
"""Pretty-print a tree.""" output = StringIO() last_row = -1 for i, n in enumerate(tree): if i: row = int(math.floor(math.log(i+1, 2))) else: row = 0 if row != last_row: output.write('\n') columns = 2**row col_width = int(math.floor((total_width * 1.0) / columns)) output.write(str(n).center(col_width, fill)) last_row = row print output.getvalue() print '-' * total_width print return pq = PriorityQueue() pq.add(5, "Sam") pq.add(23, "Sam") pq.add(3, "Sam") pq.add(45, "Sam") print pq.remove_min() print pq.remove_min() print pq.remove_min() print pq.remove_min()
""" A script representing one round of stock trading we assume each buyer and seller is looking to buy or sell exactly 100 shares. """ buyers = [{"name": "Sam", "bought": 0}, {"name": "Rickie", "bought": 0}, {"name": "Matt", "bought": 0}] sellers = [{"name": "Alex", "sold": 0}, {"name": "Daniel", "sold": 0}, {"name": "Thomas", "sold": 0}] buy_orders, sell_orders = PriorityQueue(), PriorityQueue() for e in buyers: buy_orders.add(random.randint(5, 100), e) for e in sellers: sell_orders.add(random.randint(5, 100), e) while len(buy_orders) != 0: buy = buy_orders.remove_min() if buy[0] < sell_orders.min()[0]: # add to a list for next round pass else: buy[1]["bought"] += 100 sell_orders.remove_min()[1]["sold"] += 100 for e in buyers: print e["name"] + " bought " + str(e["bought"]) + " shares"