## DEV Community is a community of 601,436 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Coding Puzzles: Week of 4/8

## Replies for: function stray(arr) { return arr.reduce((a, b) => a ^ b) }

russ

What is this necromancy?

Laurie • Edited

Haha, bitwise xor. Since it's immutable and commutative it'll reduce down to the stray!

I should add that this only works because it’s an odd number of elements in the array. An even number of matching elements cancel each other out to result in the “stray”.

russ

Oh my, it even works in python!

``````def stray(arr):
count = {}
for index, i in enumerate(arr):
count[i] = count.setdefault(i, 0) + 1
if index >= 2 and len(count.keys()) > 1:
break
return next(k for k, v in count.items() if v == 1)

from functools import reduce

def intstray(arr: [int]):
return reduce(lambda x,y: x ^ y, arr)

assert(intstray([1, 1, 2]) == 2)
#nope..!
#assert(intstray([1, 1, 2, 1]) == 2)
assert(intstray([17, 17, 3, 17, 17, 17, 17]) == 3)
assert(intstray([1, 2, 2]) == 1)
assert(stray(["bob", "bob", "bob", "steve", "bob"]) == "steve")
``````