Home > Software design >  Vector combining algorithm not working - index out of range error
Vector combining algorithm not working - index out of range error

Time:04-30

I am attempting to complete the exercise that has the following question:

Write an algorithm that takes two vectors, and creates the vector that includes the components of the given vectors without repeated elements. Example:
X = (11,20,56,2) and Y = (132,20,56,21) -> W = (11,20,56,2,132,21)

Currently this is what I have. The problem is that the program itself refuses to run because of index out of range errors.

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)

CodePudding user response:

A cleaner way to do the above task:

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

Output:

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

CodePudding user response:

Before appending to list 'y', you can check to see if the value is already in list 'y'. Using your same input code:

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)

CodePudding user response:

If you need a solution that preserves order and eliminates redundancies regardless of where they occur:

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]

Using a set will be more time efficient but less space efficient than scanning through the list that's being constructed.

  • Related