首页 > 解决方案 > Python 中的 IQ 测试功能未按预期工作

问题描述

我在下面的代码中遇到问题。

我的任务是创建一个函数,在给定的数字中找到一个不同的均匀度,并返回该数字的位置。数字以字符串形式给出。到目前为止,我已经设法将字符串转换为整数列表,然后使用for循环遍历每个数字。

我遇到的问题是我设法只返回偶数中奇数的位置,我无法继续执行反之亦然的代码,因为它只返回奇数的位置数字。

这是代码:

def iq_test(numbers):
    # Splitting the "numbers" string
    num_split = numbers.split()
    # converting the splitted strings into int
    num_map = map(int, num_split)
    # converting the object into list
    list_num = list(num_map)
    for n in list_num:
        if not n%2 == 0:
            return list_num.index(n) + 1

标签: pythonlogic

解决方案


您的问题是,您假设您正在搜索第一个偶数。你要做的,是首先决定,你在寻找什么。例如,您可以简单地首先计算偶数的数量。如果它是一个,那么你正在寻找一个偶数,否则,你正在寻找一个奇数。由于您不关心实际数字,因此我会将它们全部映射到它们的值 mod 2,如下所示:

num_map = list(map(lambda x: int(x) % 2, num_split))

然后,剩下的就很简单了。例如像这样:

def iq_test(numbers):
    # Splitting the "numbers" string
    num_split = numbers.split()
    # converting the splitted strings into even (0) or odd (1)
    num_map = list(map(lambda x: int(x) % 2, num_split))
    # return the correct position based on if even or odd is in search
    evens = num_map.count(0)
    if evens == 1:
        return num_map.index(0) + 1
    else:
        return num_map.index(1) + 1

推荐阅读