矢量组合算法不工作-索引超出范围错误



我正在尝试完成有以下问题的练习:

编写一个算法,取两个向量,并创建包含给定向量的分量且不重复元素的向量。示例:
X = (11,20,56,2)Y = (132,20,56,21)->W = (11,20,56,2,132,21)

目前这是我所拥有的。问题是程序本身因为索引超出范围错误而拒绝运行。

dimA = int(input("Introduce the dimension of A"))
dimB = int(input("Introduce the dimension of B"))
A = [0] * dimA
B = [0] * dimB
y = []
for i in range(dimA):
A[i] = int(input("Introduza elementos do vetor A"))
for i in range(dimB):
B[i] = int(input("Introduza elementos do vetor B"))
print(A)
print(B)
copia = 0
jcopia = 0
for i in range(dimA):
y.append(A[i])
for j in range(dimB):
y.append(B[j])
dimY = len(y)
for i in range(dimY):
for j in range(dimY):
if B[i] == B[j]:
copia = copia + 1
jcopia = j
while copia > 0:
y.remove(B[jcopia])
copia = copia - 1
print(y)

完成上述任务的更简洁的方法:

X=[11,20,56,2]
Y=[132,20,56,21]
W=list(set(X+Y))
print(W)

输出:

[2, 132, 11, 20, 21, 56]

在添加到列表y之前,您可以检查该值是否已经在列表y中。使用相同的输入代码:

dimA = int(input("Introduce the dimension of A"))
dimB = int(input("Introduce the dimension of B"))
A = [0] * dimA
B = [0] * dimB
y = []
for i in range(dimA):
A[i] = int(input("Introduza elementos do vetor A"))
for i in range(dimB):
B[i] = int(input("Introduza elementos do vetor B"))
print(A)
print(B)
for value in A + B:
if value not in y:
y.append(value)
print(y)

如果您需要一个保持秩序并消除冗余的解决方案,无论它们发生在哪里:

X = [11, 20, 56, 2]
Y = [132, 20, 56, 21]
W = []
s = set()
for elt in X+Y:
if elt not in s:
s.add(elt)
W.append(elt)
print(W)       # => [11, 20, 56, 2, 132, 21]

使用set将比扫描正在构造的列表更省时,但空间效率更低。

最新更新