我正在尝试编写一个插入函数。但是我很迷茫。我有一个错误:
ValueError:无缘无故不在列表中。
我的代码:
def __init__(self):
self.heap=[]
self.size = 0
def parent(self,index):
if index<=1:
return None
elif index>=self.size:
return None
else:
return self.heap[int((index-1)/2)]
def swap(self, index1, index2):
self.heap[index1-1], self.heap[index2-1] = self.heap[index2-1], self.heap[index1-1]
def insert(self,x):
self.heap.append(x)
self.size = self.size + 1
#while currentsize :
#if currentsize[x] > self.parent(self,x):
#self.swap(currentsize[x],currentsize[int((x-1)/2)])
#if x > self.parent(x):
#self.swap((currentsize.index[x])+1, currentsize.index[self.parent(x)]+1)
while self.heap.index(x)//2>0:
if self.heap.index(x)>self.heap.index(self.parent(x)):
#temp = a(x)
#a.index(x//2) = a.index(x)
#a.index(x) = temp
self.swap(self.heap.index(x),self.heap.index(self.parent(x)))
答案 0 :(得分:0)
您已经创建了self.size,但是忘记了从defs之外给它变量。我主要致力于使您的代码适用于parent()
,并进行了一些脚本固定工作。我没有检查swap
或insert
defs,但是现在您掌握了它。
请参见另一个示例,如何在另一个问题的答案中使用self
here。很多文档可以在其他地方找到。
以下代码打印:
lol [12, 13] 0 # <--- string, list, value
t1
(None, 1)
脚本:
def __init__(self, heap, size):
self.heap = heap
self.size = size
print (type(self.size))
print (self.size)
def parent(self, index):
print ('lol', self, index)
if index <= 1:
print ('t1')
return (None, 1)
elif index >= x:
print ('t2')
return (None, 2)
else:
return self.heap[int((index - 1)/2)]
def swap(self, index_1, index_2): # Using underscore gives distinction between variable name (includes stringbased values) and real values.
self.heap[index_1 - 1], self.heap[index_2 - 1] = self.heap[index_2 - 1], self.heap[index_1 - 1]
def insert(self, x):
self.heap.append(x)
self.size = self.size + 1
#while currentsize :
#if currentsize[x] > self.parent(self,x):
#self.swap(currentsize[x],currentsize[int((x-1)/2)])
#if x > self.parent(x):
#self.swap((currentsize.index[x])+1, currentsize.index[self.parent(x)]+1)
hi = self.heap.index(x) # < Reusable variable gives better readability of your script.
while hi//2 > 0:
hip = self.heap.index(self.parent(x)) # < Reusable variable gives better readability of your script.
if hi > hip:
#temp = a(x)
#a.index(x//2) = a.index(x)
#a.index(x) = temp
self.swap(hi, hip)
if __name__ == "__main__":
x = 12
y = 13
h = [x, y] # <--- list heap
s = 0 # <--- index size
q = parent(h, s)
print (q) # < prints the returned result (checkmark 1 showns which "None" is returned.
p = q[1]
#print (p) # printing p would give you '1' value.