我知道如何用Java编程,我对python非常陌生。我正在尝试用Python实现HeapSort,但是我无法理解这段代码出错的地方。有人能帮忙吗?
这就是我的实现:
class HeapSort:
def sort(self,list):
self.p = list
self.N = len(list)
for k in range(N/2,1,-1):
sink(k,N)
while N> 1:
exch(1,N)
N -=1
sink(1,N)
# Helper Functions to restore the heap invariant
def sink(k,N):
while 2*k <= N:
j = 2*k
if (j<N & (j < j+1)):
j += 1
if (j < k):
break
exch(k,j)
k = j
def exch(i,j):
p[i],p[j] = p[j],p[i]
# Helper Functions to debug
def isSorted(list):
for k in range(1,len(list)):
return False
return True
L = [6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
print(L)
h = HeapSort()
h.sort(L)
print(L) 我得到的输出是
[6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
NameError: "name 'HeapSort' is not defined"
module body in heapsort.py at line 26
class HeapSort:
function HeapSort in heapsort.py at line 64
h = HeapSort()发布于 2014-03-05 21:07:01
如果缩进是准确的,则会导致在定义HeapSort时调用HeapSort。
相反,你会想
class HeapSort():
...
def main():
L = [6, 4, 2, 8, 1, 9, 3, 0, 12, 5]
print(L)
h = HeapSort()
h.sort(L)
print(L)
if __name__ == '__main__':
main()这允许您运行定义类的文件,如果其他文件导入类,它将不会运行代码。
编辑
上面的代码将修复您正在获取的错误,但是如果您看到@Matt的注释,但是您正在heapsort.py文件中运行测试,则应该将它们移动到一个外部heapsort-tests.py文件中,并使用
from heapsort import HeapSort编辑2
如果要将其视为要使用的类,并将其作为实例化对象传递,则需要将self传递给所有方法,并使用self.method_name()调用它们,即self.sink(x,y)。如果不是,您可以通过调用类似HeapSort.sort(L)的东西来排序,而不是创建h。
https://stackoverflow.com/questions/22209160
复制相似问题