M
M
MeeLeSh2020-06-12 20:27:21
Python
MeeLeSh, 2020-06-12 20:27:21

Python. name 'heap' is not defined?

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.values[(i - 1)// 2]:
      self.values[i], self.values[(i - 1)// 2] = self.values[(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(arr):
  heap = Heap()
  for item in arr:
    heap.Insert(item)
  return heap

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

G = [7, 8, 5, 67, 21, 54, 1]
heaphy(G)
Get_sorted_arr(heap)


The error itself is:
line 52, in
Get_sorted_arr(heap)
NameError: name 'heap' is not defined

I'm new, sorry for the stupid question. Programming learning 2nd month

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Nekrasov, 2020-06-12
@MeeLeSh

Maybe something like this?

G = [7, 8, 5, 67, 21, 54, 1]
Get_sorted_arr(heaphy(G))

heap - there is a local variable and it is not in the global scope)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question