Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to know the number of positions just deleted in the list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading