I have a probleme with this excercise
I have a list of duplicate numbers like this and i don’t known how to give the position of the numbers have just been deleted
l1 = [12, 12, 3, 18, 4, 5, 3, 16, 14, 15, 12]
I expecting the result will be like this
3 numbers have been removed
12 was in position 1
3 was in position 6
12 was in position 10
>Solution :
While iterating, you can keep track of which numbers have been visited before, then store that number along with its index somewhere to report it later. Only add the numbers which haven’t been visited before to the final list(basically creating a new list without duplicate values):
def delete_duplicates_and_report(lst: list[int]) -> list[int]:
seen = set[int]()
deleted_items: list[tuple[int, int]] = []
res: list[int] = []
for i, item in enumerate(lst):
if item in seen:
deleted_items.append((i, item))
else:
res.append(item)
seen.add(item)
# reporting
print(f"{len(deleted_items)} numbers have been removed")
for i, item in deleted_items:
print(f"{item} was in position {i}")
return res
l1 = [12, 12, 3, 18, 4, 5, 3, 16, 14, 15, 12]
filtered_lst = delete_duplicates_and_report(l1)
print(filtered_lst)
output:
3 numbers have been removed
12 was in position 1
3 was in position 6
12 was in position 10
[12, 3, 18, 4, 5, 16, 14, 15]