Logic error.
- If you intend to replace the duplicate values with
0, then performing a del + list.append() is incorrect because del with remove the value while list.append() will add a new value at the end of the list, not inline. See this example.
my_list = [100, 100, 200]
print(my_list, "Original list")
del my_list[1]
print(my_list, "List after del")
my_list.append(0)
print(my_list, "List after append")
Output:
[100, 100, 200] Original list
[100, 200] List after del
[100, 200, 0] List after append
You can use del + list.insert(), but that is still inefficient. Instead, what you have to do is just re-assign the new value directly.
my_list[1] = 0
print(my_list, "List after re-assignment")
Output:
[100, 0, 200] List after re-assignment
- For every element, you are iterating all other elements but skips the current element itself. This means that if you changed a value to
0 in the next elements, once you reach that element, it would then count the other zeros as duplicates, even if those aren't meant to be counted. So pseudocode would be:
[100, 100, 200, 200] -> Original list
loop index=0
Check duplicates for item-0 which is 100
[100, 0, 200, 200] -> Sees item-1 as duplicate.
count = 1
loop index=1
Check duplicates for item-1 which is 0
No duplicates
count = 1
loop index=2
Check duplicates for item-2 which is 200
[100, 0, 200, 0] -> Sees item-3 as duplicate.
count = 2
loop index=3
Check duplicates for item-3 which is 0
[100, 0, 200, 0] -> Sees item-1 as duplicate.
count = 3
As you can see, it incorrectly counts the duplicate value of 0. A quick fix to your code is to skip the 0 elements
...
for i in range(len(list)):
if list[i] == 0:
continue
...
Better yet, redesign the logic. Instead of iterating over all elements, just iterate up to the current element only. So the idea is to loop over each element, and check if it already occurred in the past elements. To emphasize, past elements, don't iterate yet on the future elements.
- Don't use the builtin name
list. This will cause failure if you then write list(some_iterable) later.
Sample solution
my_list = [1,1,3,4,5,5,5,6]
count = 0
for i in range(len(my_list)):
for k in range(0, i):
if my_list[i] == my_list[k]:
my_list[i] = 0 # If you want the result to be [1, 0, 3, 4, 5, 0, 0, 6]
# my_list[k] = 0 # If you want the result to be [0, 1, 3, 4, 0, 0, 5, 6]
count = count + 1
break
print(count)
print(my_list)
Output
3
[1, 0, 3, 4, 5, 0, 0, 6]
Improvement
Note that your algorithm has a time complexity of O(n^2). You can lower it down to O(n) by using additional O(n) space complexity which will track already existing elements.
my_list = [1,1,3,4,5,5,5,6]
existing = set()
count = 0
for i in range(len(my_list)):
if my_list[i] in existing:
my_list[i] = 0
count += 1
else:
existing.add(my_list[i])
print(count)
print(my_list)
forloop? why notset, i.e.,my_set = set(my_list); count = len(my_set) - len(my_list)for k in range(i, len(list))otherwise you will compare with previous value from the lsit