Skip to content
Open
Show file tree
Hide file tree
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
90 changes: 90 additions & 0 deletions src/kr2/bheap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
class Node:
data = 0
level = 0
child = None
parent = None
right = None

def __init__(self, key):
self.data = key
self.level = 0
self.child = None
self.parent = None
self.right = None

def __str__(self):
return str(self.data)


class BHeap:
trees = []

def __init__(self, trees):
self.trees = trees
Comment on lines +20 to +23
Copy link

Choose a reason for hiding this comment

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

trees = [] создает общий для всех экземпляров класса список, но self.trees = trees его перекрывает


def insert(self, key):
node = Node(key)
self.merge(BHeap([node]))

def find_min(self):
mn = 10**10
for tree in self.trees:
mn = min(tree.data, mn)

if mn == 10**10:
print("No min")
return

return mn

def merge(self, heap):
self.trees.extend(heap.trees)
Comment on lines +40 to +41
Copy link

Choose a reason for hiding this comment

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

Это просто объединение двух списков



def extract_min(self):
mn = 10**10
min_node = None
for tree in self.trees:
if tree.data < mn:
mn = tree.data
min_node = tree

if mn == 10**10:
print("No min")
return

self.trees.remove(min_node)

if min_node.child:
self.merge(BHeap(min_node.child))
Copy link

Choose a reason for hiding this comment

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

BHeap ожидает список, а Вы передаете объект Node

Comment on lines +58 to +59
Copy link

Choose a reason for hiding this comment

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

Это ведет к потере детей, мы добавляем только одного ребенка удаляемой ноды


return min_node.data

def __str__(self):
res = ""
for tree in self.trees:
res += str(tree) + " "
return res


if __name__ == "__main__":
heap = BHeap([])

print(heap.find_min())
print(heap.extract_min())


heap.insert(10)
heap.insert(20)
heap.insert(30)

print(heap)
print(heap.find_min())
print(heap.extract_min())
print(heap)

print(heap.extract_min())
print(heap)



15 changes: 15 additions & 0 deletions src/kr2/test_bheap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import pytest
import bheap

def test_min():
heap = bheap.BHeap([])

heap.insert(10)
heap.insert(20)
heap.insert(30)

assert heap.find_min() == 10


if __name__ == "__main__":
pytest.main()