gpt4 book ai didi

python - python __eq__ 方法检查两个列表是否相等时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:37 25 4
gpt4 key购买 nike

我有一个Python程序,其中有一个名为Vector的类,并且该类内部有一个空列表,该列表正在运行时填充。这是初始化:

def __init__(self,n):
self.vector = [];
self.n = n;
for x in range(n):
self.vector.append(False);

这是eq:

def __eq__(self, other):
t = True
for x in range(self.n):
if self.vector[x] != other.vector[x]:
t = False;
return t

但是,当我尝试检查此类型的 2 个对象是否相等时,我总是得到 true,即使我更改了 Vector 类中向量内部的值。这是我执行上述操作的代码:

vectors = []
n = tmp.size();
k = calculateCombinationCount(n,int(n/2))
for i in range(k):
for j in range(0,n-1):
if (tmp.vector[j] != tmp.vector[j+1]):
t = True
for x in vectors:
if x == tmp:
t = False;
if t:
vectors.append(tmp)
tmp.printVector();
tmp.swap(j,j+1);

如果您能提供任何帮助,我将不胜感激。谢谢:)

编辑:

def swap(self,i,j):
tmp = self.vector[i]
self.vector[i] = self.vector[j]
self.vector[j] = tmp

def calculateCombinationCount(n,r):
k = factorial(n)/(factorial(int(r))*factorial(int(n-r)))
return int(k)

最佳答案

是的,我已经将您的代码更新为更多 pythonic (我可以看出你来自另一种语言,Java?)。

from math import factorial

class Vector:

def __init__(self, size):
self.size = size
self.vector = [False] * size

def __eq__(self, other):
"""
Same if self.size == other.size
"""
assert self.size == other.size, (self.size, other.size)
return self.vector == other.vector

def print_vector(self):
print(self.vector)

def swap(self, i, j):
"""
More efficient and pythonic
"""
self.vector[i], self.vector[j] = self.vector[j], self.vector[i]


def calculate_combination_count(n, r):
"""
This is slow, I'd replace it with scipy.special.comb
https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html#scipy.special.comb
"""
return factorial(n) // (factorial(r) * factorial(n-r))


tmp = Vector(10)

vectors = []
n = tmp.size
k = calculate_combination_count(n, n // 2)
for i in range(k):
for j in range(0, n-1):
if tmp.vector[j] != tmp.vector[j + 1]:
if not any(vec == tmp for vec in vectors): # much more efficient
vectors.append(tmp)
tmp.print_vector()
tmp.swap(j, j + 1)
else: # Just to prove why it doesn't work
print('tmp.vector is all False: {}'.format(not all(tmp.vector)))

这会重复打印出tmp.vector is all False: True。我认为这是你的问题。

如果你

关于python - python __eq__ 方法检查两个列表是否相等时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com