我有一个叫做堆的类。我在其中声明了三个单独的列表(min_list,max_list和xor_list)。调用build_heap时,它将在某些初始输入列表上创建一个堆列表。然后,我将所有三个列表(最小,最大和异或)设置为堆列表。因此,不应以任何方式链接它们。但是当我做类似的事情
self.min_list [2] =“ 6”
它将更改所有三个列表。我的代码如下:
class Heap:
def __init__(self):
self.heap_list = [None]
self.currentSize = 0
self.alist = []
self.min_list = []
self.max_list = []
self.xor_list = []
self.i = 0
self.list_start = 0
self.SCA = 0
self.interval_to = 0 # interval in initial list, not in heap numbering
self.interval_from = 0
def build_heap(self, alist):
i = 0
self.alist = alist
while len(alist) > (2**i):
i += 1
self.i = i
self.list_start = (2**self.i)
for j in range(len(alist)):
self.heap_list.insert(self.list_start + j, alist[j])
for k in range((2**self.i)-1):
self.heap_list.insert(k, None)
# append None to list
# print(len(alist))
for l in range((2**self.i)-len(alist)):
# print("lol")
self.heap_list.append(None)
tup_list = self.heap_list
self.min_list = tup_list
self.max_list = tup_list
self.xor_list = tup_list
def smallest_common_ancestor(self):
bin_from = list(bin(int(self.interval_from) + int(self.list_start))[2:])
bin_to = list(bin(int(self.interval_to) + int(self.list_start))[2:])
smallest_common_ancestor = ""
p = 0
while len(bin_to) > p:
if bin_to[p] == bin_from[p]:
print(p)
smallest_common_ancestor = smallest_common_ancestor + str(bin_to[p])
p += 1
self.SCA = int(smallest_common_ancestor, 2)
def low_id(self):
print("Min_list before change: {}".format(self.min_list))
int_from = int(self.interval_from) + int(self.list_start)
int_to = int(self.interval_to) + int(self.list_start)
m = int_to // 2
while m + 1 != self.SCA:
if (m * 2) == int_to:
self.min_list[m] = self.min_list[(m * 2)]
elif ((m*2) + 1) == int_from:
self.min_list[m] = self.min_list[(m * 2) + 1]
elif self.min_list[m * 2] is None:
if self.min_list[(m * 2) + 1] is None:
self.min_list[m] = None
else:
self.min_list = self.min_list[(m * 2) + 1]
elif self.min_list[(m * 2) + 1] is None:
self.min_list[m] = self.min_list[m * 2]
elif int(self.min_list[m * 2]) >= int(self.min_list[(m * 2) + 1]):
self.min_list[m] = self.min_list[(m * 2) + 1]
else:
self.min_list[m] = self.min_list[(m * 2)]
m -= 1
return self.min_list[self.SCA]
一开始我按照这些原则做一些事情,这不应该成为问题的一部分
heap = Heap()
heap.build_heap(input_list)
heap.interval_to,heap.interval_from = f.readline.split()
答案 0 :(得分:1)
def build_heap(self, alist):
# ...
tup_list = self.heap_list
self.min_list = tup_list
self.max_list = tup_list
self.xor_list = tup_list
这是您的班级“链接”列表的地方。 Python是按引用传递的,因此min_list
,max_list
,xor_list
,tup_list
和heap_list
将在您调用后都指向同一个对象build_heap()
。
要创建具有相同值的独立列表,您需要显式复制它们:
new_list = list(old_list)