Program problem that traverses two lists and generates a third without repeating elements

Asked

Viewed 76 times

-2

For a little over a week I’ve been trying to solve the following exercise: "Make a program that traverses two lists and generates a third without repeating elements." The statement in question is part of Exercise 6.3 of the book "Introduction to programming with Python" by Professor Nilo Menezes.

The idea of the problem presented is that the programmer creates an algorithm that reads two different lists and that a third list is produced based on these two, ignoring the elements repeated and/or already included in the new list. How this is an exercise that aims at the practice of programming logic using the new concepts learned, it must be resolved without the use of functions.

Because of this important detail, the resolution tabled here does not apply in any way, nor is the purpose of the exercise the same as redirect link.

Prof. Nile himself has posted resolution of this same exercise in your blog, but with a significantly different logic than what I’ve been trying to: I have chosen to add the items in List 1 and List 2 to List 3 independently by checking whether there are repeated elements from each list in List 3 and, if not, by adding. Due to this factor, my code is incomplete, having been written down to the first list, since the problem is in its respective loop.

I cannot say what is wrong: after inserting the values in the variables, the program simply stops running, without being terminated by the interpreter. I even thought it might be a syntax problem, but in this case I thought some message would be displayed and the program would be terminated correctly, right?

As I commented in a paragraph above, I believe the problem lies in the second nested loop.

Below is my algorithm:

# Faça um programa que percorra duas listas e gere uma terceira sem elementos repetidos.

lista_1 = []
lista_2 = []
op = ''
while op != 0:
    op = int(input(f'Digite um termo da lista 1 (0 para parar): '))
    if op != 0:
        lista_1.append(op)
    else:
        op = ''
        while op != 0:
            op = int(input(f'Digite um termo da lista 2 (0 para parar): '))
            if op != 0:
                lista_2.append(op)

indice_lista_1 = 0
indice_lista_2 = 0

lista_3 = []
indice_lista_3 = 0

while indice_lista_1 < len(lista_1):

    while indice_lista_3 < len(lista_1):
        if len(lista_3) == 0:
            lista_3.append(lista_1[indice_lista_1])  # len(lista_3) torna-se igual a 1
        else:
            if lista_1[indice_lista_1] != lista_3[indice_lista_3]:
                lista_3.append(lista_1[indice_lista_1])
                indice_lista_3 = indice_lista_3 + 1

    indice_lista_1 = indice_lista_1 + 1

print(f'A lista 1 é igual a {lista_1}')
print(f'A lista 3 é igual a {lista_3}')


lista_3 = []

I also have another draft of an attempt of mine less current. Do not include here because I did not find it relevant, but please signal me if you find it necessary.

  • I couldn’t let my question score drop. Please indicate me where I can improve my doubt to make it clearer and more useful to everyone.

  • 1

    I know it’s a drill and they probably want you to do it manually, but just for the record, in Python you can use set, which is a structure that does not allow duplicated elements, so just do terceira = list(set(primeira + segunda)). And to print, a more idiomatic form would be for i, n in enumerate(terceira): print(f"{i}: {n}")

1 answer

1


I tried to make it as simple as possible. First are comments on your code/problem, the sequence it does and why it is not working.

#From index creation up (list addition 1 is 2) everything is okay.

#In the first IF the Len of 3 is 0 so it will be initialized and the so that you passed the list 3 will receive the index 0 of the list 1 that has x elements.

#Example : If the list one was ls_1 = [1,2,3] the list 3 sera ls_3 = [1] on account of the first if.

#Soon after this change is made this first If ceases to be valid because now the list 3 has Len() != 0.

#From now on Else will run, but there is a problem, the list one Dice [0] will always be equal to the list 3 Dice [0] so your Else’s IF cannot run ,which is causing an infinite loop, even if nothing appears on the screen. To check just by print("Something") inside your Else and run the program.

#But what about that change in Dice 1 down there?? Well, it would validate and break this loop, but it was put in the "scope", identation within the first while and not the second while, and how is the second one running then never ends, because the 1/3 list entry does not change.

...My code...

lista_1 = list()
lista_2 = list()
lista_3 = list()

while True:
num = int(input("Adicionar a lista 1 : "))

if num == 0:
    break       
else:
    lista_1.append(num)     
print()

while True:
num = int(input("Adicionar a lista 2 :"))

if num == 0:
    break
else:
    lista_2.append(num)

#Here I am filtering the lists through a loop for and a conditional if, one and two,

#all items in the list_1 are played to x and pass from one to one in the if condition until no more items are left to pass. #If the number is not present in the list 3 it will be added. #Then the same process is performed with the list 2.

for x in lista_1:
if x not in lista_3:
    lista_3.append(x)

for x in lista_2:
  if x not in lista_3:
    lista_3.append(x)
        
print(f"\n{lista_3}")
  • See this topic How we should format questions and answers? may help you with the visual presentation of your content.

  • 1

    Thank you so much for the answer! And sorry for the delay in returning. I didn’t understand very well the part where you commented that the two while were equal. With your analysis I decided to do a test: I added an "Else: break" in the loop that was in infinite loop and apparently everything is working, so my question. Where the while are exactly the same?

  • 1

    I’m sorry I was wrong when I analyzed the two whiles, they are different and I kind of solved your question in the middle of the morning, happens. Ps : welcome to python :)

Browser other questions tagged

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