나는 이렇게 학습한다/Algorithm & SQL
Find the odd int
daco2020
2022. 3. 30. 21:41
반응형
Description:
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
Examples
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
Solution:
1. Count the number of identical elements.
2. If the number of elements is odd, the element is returned.
def find_it(seq):
for i in set(seq):
if seq.count(i)&1:
return i
How to solve using the collections built-in function.
import collections
def find_it(seq):
for k, v in collections.Counter(seq).items():
if v&1:
return k
반응형