M
M
MeeLeSh2020-06-12 12:31:42
Python
MeeLeSh, 2020-06-12 12:31:42

Python. Problem with implementation of heap. How to fix 'Heap' object is not subscriptable' error?

class Heap:
  def __init__(self):
    self.values = []
    self.size = 0

  def Insert(self, x):
    self.values.append(x)
    self.size += 1
    self.SwitchUp(self.size - 1)

  def SwitchUp(self, i):
    while i != 0 and self.values[i] <= self[(i - 1)// 2]:
      self.values[i], self[(i - 1)// 2] = self[(i - 1)// 2], self.values[i]
      i =(i - 1)// 2

  def ExtractMin(self):
    if not self.size:
      return None
    tmp = self.values[0]
    self.values[0] = self.values[-1]
    self.values.pop()
    self.size -= 1
    self.SwitchDown(0)
    return tmp

  def SwitchDown(self, i):
    while 2*i+1 < self.size:
      if self.values(2*i+1) < self.values(i):
        j = 2*i + 1
      if 2*i + 2 < self.size and self.values(2*i + 2) < self.values(2*i + 1):
        j = 2*i + 2
      if i == j:
        break
      self.values[i], self.values[j] = self.values[j], self.values[i]
      i = j 

def heaphy(iterable):
  heap = Heap()
  for item in iterable:
    heap.Insert(item)
  return heap

def Get_sorted_arr(heap):
  arr = []
  while heap.size:
    arr.append(heap.ExtractMin())

G = [7, 8, 5, 67, 21, 54, 1]

heaphy(G)
Get_sorted_arr(heap)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-06-12
@MeeLeSh

you have an error here:
self[(i - 1)// 2]
you are accessing an object as an array ...
ZY . And where did you learn to code in Python like that? )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question