def lastStoneWeight(self, stones):

        print("Before Heapify", stones)
        stoneHeap = MaxHeap.MaxHeap(stones)
        print("After Heapify", stoneHeap.printHeap())

        # while I have more than 2 stones
        while (len(stoneHeap.heap) > 2):
            print("Inside Loop", stoneHeap.printHeap())

            # take the max elements
            s1 = stoneHeap.pop()
            s2 = stoneHeap.pop()

            # smash them together
            if s1 > s2:
                diff = s1 - s2
            elif s2 > s1:
                diff = s2 - s1
            else:
                continue

            stoneHeap.push(diff)

        # if there are no stones left, return 0
        if len(stoneHeap.heap) == 1:
            return 0
        # otherwise return the remaining stone
        else:
            return (stoneHeap.heap[1])
def cosinus_max_heap_creator(query_res, docs_res):
    helper = CosinusArray(query_res, docs_res)
    score_final_result = []
    i = 1
    while i < len(helper.helper_array):
        score_final_result.append([
            helper.helper_array[i].id,
            single_cosinus_score(helper.helper_array[0],
                                 helper.helper_array[i])
        ])
    max_heap = MaxHeap.MaxHeap()
    for i in range(len(score_final_result)):
        max_heap.push(score_final_result[i])
    return max_heap
예제 #3
0
    def test_popMax(self):
        max_heap = MaxHeap.MaxHeap(10)
        max_heap.insert(5)
        max_heap.insert(14)
        max_heap.insert(23)
        max_heap.insert(32)
        max_heap.insert(41)
        max_heap.insert(87)
        max_heap.insert(90)
        max_heap.insert(50)
        max_heap.insert(64)
        max_heap.insert(53)
        max_heap.fullHeapify()

        self.assertEqual(max_heap.popMax(), 90)
        self.assertEqual(max_heap.popMax(), 87)
예제 #4
0
def Main():
    MH = MaxHeap.MaxHeap()
    try:
        fo = open("Cars.txt", "r")
    except IOError:
        print("No such file!")
    else:
        for line in fo.readlines():
            info = line.split()
            Make = info[0]
            Model = info[1]
            Year = int(info[2])
            Mileage = float(info[3])
            Price = float(info[4])
            newCar = Car.Car(Make, Model, Year, Mileage, Price)
            MH.heapInsert(newCar)
        fo.close()
    print("Cars information in the system are as follows:")
    MH.printHeap()
    s = menu()
    while s in range(1, 4):
        if s == 1:
            if MH.heapSize > 0:
                oldCar = MH.extractMax()
                print(
                    "The car information with the max price are Make: %s, Model: %s, Year: %d, Mileage: %.0f, Price: %.0f"
                    % (oldCar.Make, oldCar.Model, oldCar.Year, oldCar.Mileage,
                       oldCar.Price))
            else:
                print("Empty heap!")
        if s == 2:
            print("Enter the new car information you want to insert:")
            Make = input("Make: ")
            Model = input("Model: ")
            Year = int(input("Year: "))
            Mileage = float(input("Mileage: "))
            Price = float(input("Price: "))
            newCar = Car.Car(Make, Model, Year, Mileage, Price)
            MH.heapInsert(newCar)
            print("Cars information in the system are as follows:")
            MH.printHeap()
        if s == 3:
            MH.printHeap()
        s = menu()
예제 #5
0
    def test_popMax_benchmark(self):
        max_heap = MaxHeap.MaxHeap(10)
        max_heap.insert(5)
        max_heap.insert(14)
        max_heap.insert(23)
        max_heap.insert(32)
        max_heap.insert(41)
        max_heap.insert(87)
        max_heap.insert(90)
        max_heap.insert(50)
        max_heap.insert(64)
        max_heap.insert(53)
        max_heap.fullHeapify()

        input_list = np.array([5, 14, 23, 32, 41, 87, 90, 50, 64, 53])
        input_list *= -1
        expected = list(input_list)
        heapq.heapify(expected)
        expected = [-1 * _ for _ in expected]
        # Using minHeap heapify to reverse create the max heap tree yields a different result
        # expected = [90 64 87 50 53 5 23 14 32 41]
        # actual = [90 64 87 50 53 14 41 5 32 23]
        self.assertEqual(expected, max_heap)
예제 #6
0
 def __init__(self, idUser, name):
     self.idUser = idUser
     self.name = name
     # Stores all the accounts of the user in a MaxHeap.
     # The order criteria is how many times an account is used.
     self.accounts = MaxHeap.AccountsMaxHeap()
예제 #7
0
 def __init__(self):
     self.maxHeap = MaxHeap.MaxHeap()
     self.minHeap = MinHeap.MinHeap()
 def __init__(self):
     self.maxh = MaxHeap.MaxHeap()
     self.minh = MinHeap.MinHeap()
     self.medians = list()
예제 #9
0
def DijkstraHeap(graph, src, dst):
    # Initialization
    heap = MaxHeap()

    status = dict()
    width = dict()
    dad = dict()
    for v in graph.nodes():
        status[v] = 'unseen'
    status[src] = 'intree'
    for neighbor in graph.get_neighbors(src):
        status[neighbor] = 'fringe'
        width[neighbor] = graph.get_weight(src, neighbor)
        dad[neighbor] = src
        # insert into fringe heap
        heap.insert(neighbor, width[neighbor])

    while status[dst] != 'intree':
        # pick the best fringe v
        best_fringe = heap.maximum()[0]

        # put best fringe v in tree
        status[best_fringe] = 'intree'
        # heap.delete(0)
        heap.delete(best_fringe)

        for neighbor in graph.get_neighbors(best_fringe):
            weight = graph.get_weight(best_fringe, neighbor)
            if status[neighbor] == 'unseen':
                status[neighbor] = 'fringe'
                dad[neighbor] = best_fringe
                width[neighbor] = min(width[best_fringe], weight)
                # insert into fringe heap
                heap.insert(neighbor, width[neighbor])
            elif status[neighbor] == 'fringe' and width[neighbor] < min(
                    width[best_fringe], weight):
                dad[neighbor] = best_fringe
                width[neighbor] = min(width[best_fringe], weight)
                heap.delete(neighbor)
                heap.insert(neighbor, width[neighbor])

    # print results
    path = []
    last = dst
    while last != src:
        path.append(last)
        last = dad[last]

    # print('Max bandwidth path:', src, end=" ")
    # while path:
    #     print('->', path.pop(), end=" ")
    # print('\nmax bandwidth:', width[dst])

    return width[dst]
예제 #10
0
def Kruskal(graph, src, dst):

    parent = [i for i in graph.nodes()]
    rank = [0] * len(graph.nodes())

    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]

    def union(x, y):
        xr, yr = find(x), find(y)
        if xr != yr:
            if rank[xr] > rank[yr]:
                parent[yr] = xr
            elif rank[xr] < rank[yr]:
                parent[xr] = yr
            else:
                parent[xr] = yr
                rank[yr] += 1

    heap = MaxHeap()

    for edge in graph.edges():
        u, v, w = edge
        heap.insert((u, v), w)

    heap.heapSort()

    mst = MyGraph(graph.num_nodes())
    index = len(heap.H) - 1

    while find(src) != find(dst):
        # u, v = heap.H[len(heap.H)-1]
        # weight = heap.D[len(heap.D)-1]
        # heap.delete((u, v))
        u, v = heap.H[index]
        weight = heap.D[index]
        index -= 1

        ur, vr = find(u), find(v)
        if ur != vr:
            union(ur, vr)
            mst.add_edge(u, v, weight)

    color = [None] * len(mst.nodes())
    path = []
    width = {}

    for i in mst.nodes():
        color[i] = 'white'
        width[i] = math.inf
    path.append(src)

    def dfs(src, dst, color, path, width):
        if src == dst:
            return path, width[dst]
        color[src] = 'grey'
        for neighbor in mst.get_neighbors(src):
            if color[neighbor] == 'white':
                width[neighbor] = min(width[src],
                                      mst.get_weight(src, neighbor))
                path.append(neighbor)
                path, width[dst] = dfs(neighbor, dst, color, path, width)
                if dst in path:
                    return path, width[dst]
        color[src] = 'black'
        path.remove(src)
        return path, width[dst]

    dfs(src, dst, color, path, width)

    # # print results
    # print('Max bandwidth path:', path.pop(0), end=" ")
    # while path:
    #     print('->', path.pop(0), end=" ")
    # print('\nmax bandwidth:', width[dst])

    return width[dst]
예제 #11
0
def main():
    """Main method, does some testing."""
    print( "*** Initializing new MaxHeap ... done." )
    print( "*** Adding values 7, 42, 999, 0, 212, 512, 21 ... done." )

    test = MaxHeap()

    test.insert( 7   )
    test.insert( 42  )
    test.insert( 999 )
    test.insert( 0   )
    test.insert( 212 )
    test.insert( 512 )
    test.insert( 21  )

    print( "   ### Current MaxHeap: " )
    test.println()
    print( "\n   ### Number of Nodes: " + str( test.getSize() ))

    print( "\n*** Performing \"deleteMax\" ... done." )
    test.deleteMax()

    print( "   ### Current MaxHeap: " )
    test.println()
    print( "\n   ### Number of Nodes: " + str( test.getSize() ))
예제 #12
0
파일: 1.py 프로젝트: srinskit/LabSem3
from MaxHeap import *
l = [10, 45, 21, 44, 22, 14, 20, 40, 100, 32, 56, 12, 54]
max_heap1 = MaxHeap()
for element in l:
    max_heap1.insert(element)
ssl = sorted(l, reverse=True)
sl1 = []
while max_heap1.maximum() is not None:
    sl1.append(max_heap1.extract_max())
print(ssl)
print(sl1)
max_heap2 = MaxHeap(l)
sl2 = []
while max_heap2.maximum() is not None:
    sl2.append(max_heap2.extract_max())
print(sl2)
예제 #13
0
from MaxHeap import *

points = [2, 22, 33, 20, 54, 1, 6, 8, 9, 10, 22, 3]
n = 2

myHeap = MaxHeap(points[0:n])

for point in points[n:]:
    if point < myHeap.peak():
        myHeap.pop()
        myHeap.push(point)
print(myHeap)
예제 #14
0
import MaxHeap
import MinHeap

min_heap = []
max_heap = []

current_median = 0.0

stream = [6, 1, 5, 2, 4, 3, 1, 7, 7, 8]

for value in stream:
    if current_median > value:
        MaxHeap.push_heap(max_heap, value)
    else:
        MinHeap.push_heap(min_heap, value)

    current_median = value

    if len(max_heap)-len(min_heap) > 1:
        max_value = MaxHeap.pop_heap(max_heap)
        MaxHeap.push_heap(min_heap, max_value)
    elif len(min_heap)-len(max_heap) > 1:
        min_value = MinHeap.pop_heap(min_heap)
        MinHeap.push_heap(max_heap, min_value)

    if len(max_heap) == len(min_heap):
        current_median = (max_heap[0]+min_heap[0])/2
    elif len(max_heap) > len(min_heap):
        current_median = max_heap[0]
    else:
        current_median = min_heap[0]