Guest User

Untitled

a guest
Jul 23rd, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. class Heap:
  2. def __init__(self, compare):
  3. self.compare = compare
  4. self.data = []
  5.  
  6. def _swap(self, a, b):
  7. buf = self.data[a]
  8. self.data[a] = self.data[b]
  9. self.data[b] = buf
  10.  
  11. def _heapify(self, i):
  12. left = 2 * i
  13. right = left + 1
  14. largest = i
  15.  
  16. if left < len(self.data) and self.compare(self.data[left], self.data[largest]):
  17. largest = left
  18. if right < len(self.data) and self.compare(self.data[right], self.data[largest]):
  19. largest = right
  20. if largest != i:
  21. self._swap(i, largest)
  22. self._heapify(largest)
  23.  
  24. def push(self, element):
  25. self.data.append(element)
  26. i = len(self.data) - 1
  27. while i > 0 and self.compare(self.data[i], self.data[i // 2]):
  28. self._swap(i, i // 2)
  29. i = i // 2
  30.  
  31. def pop(self, element=None):
  32. rv = self.data[0]
  33. self.data[0] = element if element is not None else self.data[len(self.data) - 1]
  34. self.data.pop(len(self.data) - 1)
  35. self._heapify(0)
  36. return rv
  37.  
  38. @classmethod
  39. def build(cls, compare, arr):
  40. heap = cls(compare=compare)
  41. heap.data = arr
  42. for i in range(len(arr) // 2 - 1, -1, -1):
  43. heap._heapify(i)
  44. return heap
  45.  
  46. @property
  47. def top(self):
  48. return self.data[0]
  49.  
  50. def __len__(self):
  51. return len(self.data)
  52.  
  53. def __repr__(self):
  54. return str(self.data)
  55.  
  56. def print(self):
  57. i = 1
  58. while i <= len(self.data):
  59. print(self.data[i-1:i*2-1])
  60. i *= 2
  61.  
  62.  
  63. def less(a, b):
  64. return a < b
  65.  
  66.  
  67. def more(a, b):
  68. return a > b
  69.  
  70.  
  71. def main():
  72. h = Heap.build(more, [1, 2, 4, 10, 5, 6, 8, 11, 9, 16])
  73. print(h.data)
  74. h.print()
  75.  
  76.  
  77. if __name__ == '__main__':
  78. main()
Add Comment
Please, Sign In to add comment