Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions src/kr2/binomial_heap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import heapq

priority_queue = []
heapq.heappush(priority_queue, (2, "One"))
heapq.heappush(priority_queue, (1, "Two"))
heapq.heappush(priority_queue, (3, "Three"))
while priority_queue:
priority, task = heapq.heappop(priority_queue)
Comment on lines +3 to +8
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?


class Node:
def __init__(self):
self.data = key
Comment on lines +11 to +12
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы используете переменную key, которую не передаете в функцию.
Соответственно все вызовы вида temp = Node(key) не будут работать.

self.degree = 0
self.parent = None
self.child = None
self.parent = None
Comment on lines +14 to +16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.parent инициализируется дважды

self.sibling = None

# соединение двух биномиальных куч
def mergeBinomialTrees(b1, b2):
if b1.data > b2.data:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему не обрабатываются остальные случаи? Если b1.data <= b2.data функция вернет None.

b1, b2 = b2, b1
b2.parent = b1
b2.sibling = b1.child
b1.child = b2
b1.degree += 1

return b1

def unionBinomialHeap(l1, l2):
_new = []
it = ot = 0
while (it < len(l1)) and (ot < len(l2)):
if l1[it].degree <= l2[ot].degree:
_new.append(l1[it])
it+=1
else:
_new.append(l2[ot])
ot += 1

while it < len(l1):
_new.append(l1[it])
it += 1
while ot < len(l2):
_new.append(l2[ot])
ot += 1

return _new
Comment on lines +20 to +48
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему эти функции определены внутри функции __init__?


def adjust(_heap):
if len(_heap) <= 1:
return _heap
new_heap = []
it1 = it2 = it3 = 0
if len(_heap) == 2:
it2 = 1
it3 = len(_heap)
else:
it2 = 1
it3 = 2

while it1 < len(_heap):
if it2 == len(_heap):
it1 += 1

elif _heap[it1].degree < _heap[it2].degree:
it1 += 1
it2 += 1
if it3 < len(_heap):
it3 += 1

elif it3 < len(_heap) and _heap[it1].degree == _heap[it2].degree == _heap[it3].degree:
it1 += 1
it2 += 1
it3 += 1

elif _heap[it1].degree == _heap[it2].degree:
_heap[it1] = mergeBinomialTrees(_heap[it1], _heap[it2])
del _heap[it2]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы итерируетесь по этому циклу при помощи индексов и удаляете элементы из него, это приведет к IndexError.

if it3 < len(_heap):
it3 += 1
Comment on lines +62 to +81
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Есть подозрение, что в текущей реализации это может зависнуть, например если сделать так:

def test():
    node_deg1 = Node(10)
    node_deg1.degree = 1

    node_deg0 = Node(20)
    node_deg0.degree = 0
    
    broken_heap = [node_deg1, node_deg0]
    
    Node.adjust(broken_heap)

return _heap

def InsertATreeInHeap(_heap, tree):
temp = tree
temp = unionBinomialHeap(_heap, tree)
return adjust(_heap)


def removeMinFromTreeReturnBHeap(tree):
heap = []
temp = tree.child

# создаем кучу детей минимального элемента
while temp:
lo = temp
temp = temp.sibling
lo.sibling = None
heap.insert(0, lo)

return heap


# добавляем в биномиальную кучу
def insert(_head, key):
temp = Node(key)
return insertATreeInHeap(_head, temp)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У Вас метод называется InsertATreeInHeap



def getMin(_heap):
temp = _heap[0]

# ищем минимальный элемент в куче
for node in _heap:
if node.data < temp.data:
temp = node

return temp

def extractMin(_heap):
new_heap = []
lo = []

temp = getMin(_heap)

# удаляем минимальный элемент кучи
for node in _heap:
if node != temp:
new_heap.append(node)

# соединяем кучу с детьми минимального элемента
lo = removeMinFromTreeReturnBHeap(temp)
new_heap = unionBionomialHeap(new_heap, lo)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unionBinomialHeap

new_heap = adjust(new_heap)

return new_heap