LocalDogeCoder
LocalDogeCoder

Reputation: 83

Find position of duplicate elements in list

Basically I want to find and print the positions of all the duplicate elements. Here is my code:

numbers = [7,1,3,6,4,2,5,9,8,10]
n = int(input("Enter a number from 1 to 10 to search for the number's position: "))

def findNum():
    count = 0
    while numbers[count] != n:
        count += 1

    numPos = count + 1
    print(numPos)


if n in numbers:
    print("Calculating position... (takes 9 years so wait)")
    findNum()
    
else:
    print("Number not found, next time enter a number from 1 to 10!")

For example I add an extra 7 to numbers:

numbers = [7,1,3,6,4,2,5,9,8,10,7]

Then I want to return the 1st 7's position and also the other 7's position. How to do it?

Upvotes: 1

Views: 1813

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

To get all duplicates use a dictionary with the keys as the numbers in the list and the values the positions, to get the positions use enumerate:

from collections import defaultdict

numbers = [7, 1, 3, 6, 4, 2, 5, 9, 8, 10, 7]
duplicates = defaultdict(list)

# iterate over positions and numbers simultaneously
for i, number in enumerate(numbers):
    # accumulate positions to the same number
    duplicates[number].append(i)

result = {key: value for key, value in duplicates.items() if len(value) > 1}
print(result)

Output

{7: [0, 10]}

As you can see from the output it returns that 7 appears in position 0 an 10. The overall complexity of this approach is O(n).

The loop:

# iterate over positions and numbers simultaneously
for i, number in enumerate(numbers):
    # accumulate positions to the same number
    duplicates[number].append(i)

group the different positions (i in the code) by the same number. Using a defaultdict.

The expression:

result = {key: value for key, value in duplicates.items() if len(value) > 1}

is a dictionary comprehension, see some more info here.

Upvotes: 3

numbers = [7,1,7,6,4,2,5,9,8,10,7]
m=[]
for i in range(len(numbers)):
    for j in range(i+1,len(numbers),1):
        if(numbers[i]==numbers[j]):
            m.append(i)
            m.append(j)
l=list(set(m))
for i in range(len(l)):
    print("First Occurence at position:{}".format(l[i]))

Upvotes: 0

Related Questions