首页 > 解决方案 > 检查每个偶数索引是否包含偶数并且每个奇数索引是否包含给定列表的奇数的程序存在问题

问题描述

伙计们。我刚刚开始学习编码并且我选择了 Python,所以我的问题将是相当基本的 :) 所以,我必须编写一个 Python 程序来检查每个偶数索引是否包含偶数和每个奇数索引包含给定列表的奇数个。这是我的解决方案:

def check_the_list(a):
    for i in range(0, len(a)):
        if a[i] % 2 == 0 and i % 2 == 0 and a[i + 1] % 2 == 1 and (i + 1) % 2 == 1:
            output = True
        else:
            output = False
    return print(output)


check_the_list([2, 1, 4, 3, 6, 7, 6, 3])
check_the_list([2, 1, 4, 3, 6, 7, 6, 4])

PyCharm 表示两个列表的输出都是 False,尽管如您所见,最后一个元素是不同的。因此,有人可以向我解释我的代码有什么问题吗?非常感谢!

标签: pythonpython-3.xlist

解决方案


这里有两个问题。首先,您需要根据以下伪代码修复条件语句的逻辑:if (number AND its index are even) OR (number AND its index are odd)。其次,根据您构建代码的方式,输出变量的值将在 True 和 False 之间来回翻转,直到到达列表的末尾,然后该函数仅返回最后一项的条件。因此,如果最后一项恰好是偶数索引处的偶数,即使前面的数字不符合条件,它也会返回 True。这不是你想要的。您有一个更严格的标准,您希望每个数字都满足此条件。这就是你的做法:

def check_the_list(a):
    for i in range(0, len(a)):
        output = True
        if (a[i] % 2 == 0 and i % 2 == 0) or (a[i] % 2 == 1 and (i) % 2 == 1):
            continue
        else:
            output = False
    return output

更有效的实现是使用 not 运算符并在数字不符合条件时返回 False:

def check_the_list(a):
    for i in range(0, len(a)):
        if not ((a[i] % 2 == 0 and i % 2 == 0) or (a[i] % 2 == 1 and (i) % 2 == 1)):
            return False
    return True

print(check_the_list([2, 1, 4, 3, 6, 7, 6, 3])) #True
print(check_the_list([2, 1, 4, 3, 6, 7, 6, 4])) #False

推荐阅读