Skip to content

Commit

Permalink
simpligy parent, leftchild, and rightchild method
Browse files Browse the repository at this point in the history
  • Loading branch information
Xuefeng-Zhu committed May 14, 2015
1 parent 2d1c7e7 commit ccb9099
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions heaps/minheap.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ def __init__(self, nums=None):
self.heap = []
if nums:
self.build_heap(nums)

def __str__(self):
return "Min-heap with %s items" % (len(self.heap))

def max_elements(self):
return len(self.heap)

def height(self):
return math.ceil(math.log(len(self.heap))/math.log(2))
return math.ceil(math.log(len(self.heap)) / math.log(2))

def is_leaf(self, i):
""" returns True if i is a leaf node """
Expand All @@ -29,18 +29,14 @@ def parent(self, i):
if i == 0:
return []
elif i % 2 != 0: # odd
return (i-1)/2
return int(math.floor((i-1)/2))
return (i - 1) / 2
return (i - 2) / 2

def leftchild(self, i):
if not self.is_leaf(i):
return 2*i+1
return []
return 2 * i + 1

def rightchild(self, i):
if not self.is_leaf(i):
return 2*i+2
return []
return 2 * i + 2

def heapify(self, i):
l = self.leftchild(i)
Expand All @@ -60,8 +56,7 @@ def build_heap(self, elem):
self.heap = elem[:]
last_leaf = int(math.ceil( (len(self.heap)- 2) / 2))
for i in range(last_leaf, -1, -1):
self.heapify(i)

self.heapify(i)

def heappush(self, x):
""" Adds a new item x in the heap"""
Expand Down

0 comments on commit ccb9099

Please sign in to comment.