Skip to content Skip to sidebar Skip to footer

Remove An Even/odd Number From An Odd/even Python List

I am trying to better understand list comprehension in Python. I completed an online challenge on codewars with a rather inelegant solution, given below. The challenge was: Given

Solution 1:

Your attempt fails because the first if is always going to be true. You'll always have a list with at least 1 element; either the odd one out is odd and you tested a list with all even numbers, otherwise you have a list with the one even number in it. Only an empty list would be false.

List comprehensions are not the best solution here, no. Try to solve it instead with the minimum number of elements checked (the first 2 elements, if they differ in type get a 3rd to break the tie, otherwise iterate until you find the one that doesn't fit in the tail):

def find_outlier(iterable):
    it = iter(iterable)
    first= next(it)
    second= next(it)
    parity =first%2
    if second%2!= parity:
        # odd oneoutisfirstorsecond, 3rd will tell which
        returnfirst if next(it) %2!= parity elsesecondelse:
        # the odd oneoutis later on; iterate until we find the exception
        return next(i for i in it if i %2!= parity)

The above will throw a StopIteration exception if there are either fewer than 3 elements in the input iterable, or there is no exception to be found. It also won't handle the case where there is more than one exception (e.g. 2 even followed by 2 odd; the first odd value would be returned in that case).

Solution 2:

What are the shortcomings of this response (which is at the top of the solution stack on this particular challenge)?

deffind_outlier(int):
    odds = [x for x inintif x%2!=0]
    evens= [x for x inintif x%2==0]
    return odds[0] iflen(odds)<len(evens) else evens[0]

Solution 3:

The most efficient answer is going to get a little ugly.

def f(in_list):
    g = (i for i in in_list)
    first = next(g)
    second = next(g) #The problem as described doesn't make sense for fewer than 3 elements.  Let them handle the exceptions.if first%2 == second%2:
        a = first%2
        for el in g:
            if el%2 != a:
                return el
    else:
        third = next(g)
        if third%2 == first%2:
            return second
        else:
            return first
    except ValueError('Got a bad list, all evens or all odds')

Post a Comment for "Remove An Even/odd Number From An Odd/even Python List"