Vector union in Python

Asked

Viewed 240 times

2

Hello, I need to make a union between two vectors in python, but without using list functions for some reason my code is going wrong was to get out 7, 2, 5, 8, 4, 9, but it’s coming out as 7, 2, 5, 8, 4, 4, 2, 9, 5

def union (x,y):
  aux1 = x+y
  aux2 = []
  aux3 = " "

  for i in aux1: 
    if i not in aux2:
      aux3 += str(i) + ' '
  return aux3

a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]
print(union(a,b))

2 answers

2

To make the union, you can modify the function by adding the lists a and b and turning them into a set (who is responsible for removing duplicate values).

Would look like this:

def union(x, y):
  aux3 = ''
  s = set(x + y)
  for i in s:
    aux3 += str(i) + ' '
  return aux3

a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]

print(union(a, b))

EDIT: If you can’t use set, maybe this will solve the problem:

def union(x, y):
  aux3 = ''
  x.extend(i for i in y if i not in x)
  for i in x:
     aux3 += str(i) + ' '
  return aux3

a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]

print(union(a, b))

Or even if you prefer to use your original code, just left to add the numbers in the list aux2:

def union (x,y):
  aux1 = x+y
  aux2 = []
  aux3 = ""

  for i in aux1: 
    if i not in aux2:
      aux3 += str(i) + ' '
      aux2.append(i) # ou aux2 += [i]
  return aux3

a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]
print(union(a,b))
  • So my teacher, is forcing the staff to n use no list function other than Len, only the vector functions we can use

2

You have created an empty list (or vector), aux2. And you are checking (if not in) on this empty list (and you do not add anything during the function). Since you cannot use the functions in the list, and therefore you need to use a string instead of a list to store the result, you should then check whether the number to be added to the aux3 is in the string aux3.

aux1 = x+y
# Pode se descartar aux2, deixarei o nome como aux3 para facilitar a visualização
aux3 = ''

for i in aux1:
     # Nesse 'if' é necessário que você faça a checagem, criando uma função
     # No caso eu dei exemplo a função checar
     if i not in aux3:
          aux3 += str(i) + ' '
return aux3
  • I must have the mentality of a primate, because I really don’t understand what you mean seriously

  • Basically, you’re checking to see if the number is in an empty array, so you’re adding repeated numbers. What you should do is, check if the number is in the string aux3. I’ll give you an example of code in the comment above

Browser other questions tagged

You are not signed in. Login or sign up in order to post.