Basically I want to make my code in such a way that it finds position of the duplicate elements and prints both of them 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!")
Basically lets say I add an extra 7 to my numbers array
numbers = [7,1,3,6,4,2,5,9,8,10,7]
So then I want to return the 1st 7's position and also the other 7's position
If anyone know how to do it, please help
CodePudding user response:
To get all duplicates use a dictionary with the keys as the numbers in the list and the values the positions:
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).
CodePudding user response:
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]))