K
K
Kirill Palchevsky2022-01-19 16:32:13
Python
Kirill Palchevsky, 2022-01-19 16:32:13

How to find among the elements of the list one whose parity is unique?

Given an array that has length at least 3 and contains integers. An array is either entirely of odd integers, or entirely of even integers except for one integer N.
You need to write a function that takes an array as an argument and returns this N exception.

An example of arrays:

[2, 4, 0, 100, 4, 11, 2602, 36] - 11
[160, 3, 1719, 19, 11, 13, -21] - 160

Code I have implemented:

def find_outlier(integers):
    if sum(integers) % 2 == 1: 
        return [y for y in integers if y % 2 == 1][0]
    else:
        return [x for x in integers if x % 2 == 0][0]

Unfortunately, the algorithm fails on some tests, for example:

[-9414011, 6617441, 9673581, 4326209, -2899849, 9923397, -2291281, -5434819, 8837901, 3041829, -1378743, 3743373, 3511523, 9455891, -1351663, 4948885, 5353785, 4909097, -4585903, -6153616]

Expected: -6153616.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2022-01-19
@OffHand1424

You can't check the amount. After all, if there are even numbers in the array, then the sum will always be odd (be even one or n-1 in the array).
You can compare the first three numbers, see if your exception is there or understand what parity it should be and then find it like you have.

A
alexbprofit, 2022-01-19
@alexbprofit

def foo(array):
  return list(filter(lambda s: s% 2 if len([el for el in array if el % 2]) == 1 else s%2 + 1,array))[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question