+ 2

Why the code2 does not work? SOLVED

#Дан список. Необходимо вывести уникальные элементы списка. #A list is given. It is necessary to display the unique elements of the list. Below are 2 solutions for the task. I don't understand why the second code (which is mine) does not work. They seem me the same 🤷 lst1 = [1, 3, 2, 3, 5, 2, 7, 8] #code1 for i in range(n): for j in range(n): if i != j and lst1[i] == lst1[j]: break else: print(lst1[i], end="") print() #code2 for i in range(n): for j in range(i+1, n): if lst1[i] == lst1[j]: break else: print(lst1[i], end="")

18th Jul 2021, 7:32 AM
Елена Леващева
Елена Леващева - avatar
6 Respostas
+ 6
Елена Леващева , even if the issue is solved, you may be interested in a code that looks less complex and has a good readability (but it uses function count()): lst = [1, 3, 2, 3, 5, 2, 7, 8] for num in lst: if lst.count(num) == 1: print(num,end=" ")
18th Jul 2021, 11:20 AM
Lothar
Lothar - avatar
+ 4
In code 2, the inner loop starts at the index after i. So with every iteration of i, you are comparing each number to less and less elements. When you reach i=3 (value 3) the inner loop only checks index 4 to 7 and does not find the duplicate at index 1
18th Jul 2021, 7:37 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Tibor Santa Thanks a lot. i got it so great
18th Jul 2021, 7:59 AM
Елена Леващева
Елена Леващева - avatar
+ 2
Vasiliy thank you very much for showing codes work. It helped a lot.
18th Jul 2021, 11:58 AM
Елена Леващева
Елена Леващева - avatar
+ 1
Lothar thanks a lot for your. Great code. I am certainly interested.
18th Jul 2021, 11:50 AM
Елена Леващева
Елена Леващева - avatar