patternpythonMinor
Codewars "Find the Parity Outlier" code
Viewed 0 times
thecodewarsparityoutlierfindcode
Problem
I completed this Codewars exercise. Here are the instructions:
You are given an array (which will have a length of at least 3, but
could be very large) containing integers. The integers in the array
are either entirely odd or entirely even except for a single integer
N. Write a method that takes the array as an argument and returns N.
For example:
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160
Any comments on the following code appreciated. (I used Python 2.7)
You are given an array (which will have a length of at least 3, but
could be very large) containing integers. The integers in the array
are either entirely odd or entirely even except for a single integer
N. Write a method that takes the array as an argument and returns N.
For example:
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160
Any comments on the following code appreciated. (I used Python 2.7)
def ifeven(list):
#Determine if we are dealing with list of evens or odds
sum = 0
for ran in (0,1,2):
sum += abs(list[ran])%2
avg = float(sum)/3
r_avg = round(avg)
return r_avg == 0
def find_outlier(integers):
even = ifeven(integers)
new = []
for num in integers:
new.append(num%2)
if even:
loc = new.index(1)
else:
loc = new.index(0)
return integers[loc]Solution
The code in the post, and the code in the answers by Joe Wallis and 200_success, traverses the whole of the input to collect the parities of all the items. But it is easy to return the result as soon as the outlier has been identified, avoiding a wasted traversal of the remainder of the input.
def outlier(it):
"""Given an iterable with at least 3 items, all of which have the
same parity except for a single outlier, return the outlier.
"""
count, item = [0, 0], [None, None]
for n in it:
parity = n % 2
if count[parity] == 0 and count[1 - parity] >= 2:
return n
elif count[1 - parity] == 1 and count[parity] >= 1:
return item[1 - parity]
count[parity] += 1
item[parity] = n
else:
raise ValueError("bad iterable")Code Snippets
def outlier(it):
"""Given an iterable with at least 3 items, all of which have the
same parity except for a single outlier, return the outlier.
"""
count, item = [0, 0], [None, None]
for n in it:
parity = n % 2
if count[parity] == 0 and count[1 - parity] >= 2:
return n
elif count[1 - parity] == 1 and count[parity] >= 1:
return item[1 - parity]
count[parity] += 1
item[parity] = n
else:
raise ValueError("bad iterable")Context
StackExchange Code Review Q#132015, answer score: 3
Revisions (0)
No revisions yet.