Finding the odd number out in an array
An easier (and more efficient) way of doing this than your initial approach is with a Counter
object:
from collections import Counter
singlet = Counter(nums).most_common()[-1][0]
The Counter
object will create a dictionary-like object with the keys being the values in your list and the values being the number of times they appear. The most_common
method will return a list of tuples of (value, count)
sorted by count in decreasing order.
If you don't know how many singlets there will be, you can get a list of them with:
[k for k, v in Counter(nums).items() if v == 1]
Complexity:
I said my top solution was more efficient because your original implementation iterates through your list and for each item calls both remove
and in
which is going to get you to something like O(n2) complexity. In the Counter implementation the construction of the Counter
object only does a single pass through the entire list. There is probably a sort going on when @Stefan Pochman has corrected me on this: Python uses the Timsort algorithm which will be very efficient in a case like this (if all but one of the numbers appear twice, the list is effectively almost completely sorted already) so its complexity will about about O(n).most_common
is called so I'm guessing the complexity is about O(n log n).
You already nums_copy.remove(i)
so you can't nums_copy.remove(i)
again
You could do:
a = [0, 0, 1, 1, 2, 2, 6, 6, 9, 10, 10]
def get_single_instance(array):
d = {}
for item in a:
if item not in d:
d[item] = 1
else:
d[item] += 1
print d
for k, v in d.iteritems():
if v == 1:
return k
print get_single_instance(a)
Result: 9
The best algorithm is to use XOR to find the odd number.
def find_number(nums):
s = 0
for n in nums:
s ^= n
return s
a = [0, 0, 1, 1, 2, 2, 6, 6, 9, 10, 10]
print(find_number(a))