在奇/偶整数列表中查找奇偶校验离群值 [英] Finding the Parity Outlier in a list of odd/even integers

查看:86
本文介绍了在奇/偶整数列表中查找奇偶校验离群值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找并返回一个奇数整数列表中的单个偶数整数或一个偶数整数列表中的唯一奇数整数.我的代码有效,但是,如果列表中奇数整数的长度为偶数,它将返回列表中的第一个数字,而不是偶数整数.任何帮助表示赞赏.下面的代码:

I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:

    even = [2, 4, 6, 8, 10, 12, 14, 2091] #2091 is the outlier and len(x) = 8
    odd = [1, 3, 5, 7, 9, 11, 13, 4720] #4720 is the outlier and len(x) = 8

def find_outlier(x):
    # Determine if list is even and length of list is odd
    if sum(x) % 2 != 0 and len(x) % 2 != 0:
        for x in x:
            if x % 2 != 0:
                return x
    # Determine if list is even and length of list is even
    elif sum(x) % 2 != 0 and len(x) % 2 == 0:
        for x in x:
            if x % 2 != 0:
                return x
    # Determine if list is odd and length of list is odd
    elif sum(x) % 2 == 0 and len(x) % 2 != 0:
        for x in x:
            if x % 2 == 0:
                return x
    # Determine if list is odd and length of list is even (PROBLEM)
    elif sum(x) % 2 == 0 and len(x) % 2 == 0:
        for x in x:
            if x % 2 == 0:
                return x

print (find_outlier(even))
print (find_outlier(odd))

下面是从德米特里的解决方案重新格式化后的问题的正确解决方案:

Below is the correct solution to the problem reformatted from Dmitri's solution:

def find_outlier(x):
    odd = [i for i in x if i % 2 != 0]
    even = [i for i in x if i % 2 == 0]
    return odd[0] if len(odd) < len(even) else even[0]

推荐答案

您为什么根本不关心长度?这是更简单的解决方案:

Why do you care about the length at all? Here is much simpler solution:

def find_outliner(a):
    if a[0] % 2 != a[1] % 2:
        return a[0] if a[2] % 2 == a[1] % 2 else a[1]
    for i in a:
        if i % 2 != a[0] % 2:
            return i

它如何工作?

  1. 列表中至少应包含三个元素,否则该问题就没有太大意义
  2. 如果前两个元素的奇偶性不同,请根据第三个元素检查哪个元素是错误的(如果第二个和第三个元素的奇偶性相同,则第一个是错误的,否则-第二个是错误的)
  3. 如果前两个元素具有相同的奇偶校验,则意味着第一个(和第二个)元素的奇偶校验是list的正确奇偶校验.因此,我们正在寻找具有奇偶校验的元素.

这篇关于在奇/偶整数列表中查找奇偶校验离群值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆