Пример #1
0
    """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()
Пример #2
0
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"

for e in sellers:
    print e["name"] + " sold " + str(e["sold"]) + " shares"