0

I'm trying to write a code which returns ALL indices of the elements from a list, which are repeated EXACTLY TWICE. I'm having trouble with my own algorithm. My code only returns the FIRST occurrence it finds. I want this fixed. Here's my own code (it's somehow weird, I know):

from collections import Counter 

length = int(input())
user_input = [int(x) for x in input().split()]
occurrances = Counter(user_input)
check_list = []
check_list.append(list(occurrances.keys())[list(occurrances.values()).index(2)])
print(check_list)

I appreciate any help from anyone. Thanks in advance.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Liana
  • 314
  • 5
  • 15

4 Answers4

1

Try this:

from collections import Counter

userInput = input().split()
counter = Counter(userInput)
print([x[0] for x in counter.items() if x[1] == 2])
saulspatz
  • 5,011
  • 5
  • 36
  • 47
  • That's it! Thank you thank you thank you!! :)) – Liana Jan 29 '21 at 17:11
  • 1
    Minor improvement (in both readability and performance): `[val for val, cnt in counter.items() if cnt == 2]`. Using names makes it clearer, and unpacking to names and reading from local names is more efficient than repeated indexing (at least on CPython reference interpreter). Also, `userInput` should be `map(int, input().split())` or (if `list` needed anyway) `[int(x) for x in input().split()]` to match OP's type conversion. – ShadowRanger Jan 29 '21 at 18:42
0

This should work if you are looking for the indexes


from collections import Counter 

user_input = [int(x) for x in input().split()]
occurrences = Counter(user_input)
keys = [key for key in occurrences.keys() if occurrences[key]==2 ]
check_list = [x for x in range(len(user_input)) if user_input[x] in keys]

print(check_list)
SAB6
  • 311
  • 2
  • 6
  • Why unpack to `value`, then ignore it and use `occurrences[key]` instead? You've got `value`, you don't need to look it up again? If you're going to look it up anyway, `.items()` serves no purpose. – ShadowRanger Jan 29 '21 at 18:43
0

To find the indices of the items occurring twice.

>>> L = [1,2,3,1,4,6,6]
>>> from collections import Counter
>>> c = Counter(L)
>>> for key in filter(lambda x: c[x] == 2, c):
    one = L.index(key)
    two = L.index(key, one+1)
    print(key, 'found at indexes', ' '.join(map(str, [one, two])))


1 found at indexes 0 3
6 found at indexes 5 6
Chris Charley
  • 6,403
  • 2
  • 24
  • 26
0

To get the indexes you can use Counter and enumerate inside a list comprehension:

from collections import Counter

L  = [1,2,3,4,3,4,2,3,5]
L2 = [i for c in [Counter(L)] for i,v in enumerate(L) if c[v]==2]

print(L2)
[1, 3, 5, 6] 

If you're not allowed to use libraries, you can do it without Counter (although it will run slower):

L2 = [i for i,v in enumerate(L) if L.count(v)==2]
Alain T.
  • 40,517
  • 4
  • 31
  • 51