python – How to display an even number from the list if all other values ​​are odd, and vice versa?

Question:

Lists can be of two types, with all even numbers and one odd, and with all odd numbers and one even. There can be at least three values ​​in the list.

Example lists:

[2, 4, 0, 100, 4, 11, 2602, 36] # должно вывести 11 (как одно нечетное)
[160, 3, 1719, 19, 11, 13, -21] # должно вывести 160 (как одно четное)

How to write code to display exactly one different number?

Answer:

For example like this (provided that there are 3 elements, otherwise it is impossible to determine which is more):

res = [max, min][sum(x % 2 for x in l[:3]) > 1](l, key=lambda x: x % 2)
Scroll to Top