python - 检查每个偶数索引是否包含偶数并且每个奇数索引是否包含给定列表的奇数的程序存在问题
问题描述
伙计们。我刚刚开始学习编码并且我选择了 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,尽管如您所见,最后一个元素是不同的。因此,有人可以向我解释我的代码有什么问题吗?非常感谢!
解决方案
这里有两个问题。首先,您需要根据以下伪代码修复条件语句的逻辑: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
推荐阅读
- android - 问题将 Xamarin Forms Android 应用程序作为捆绑包发布到 Play 商店 - 文档已过期
- javascript - 如何使嵌套插槽的道具(Vue 2)可以访问父数据?
- algorithm - 砖在墙上的排列方式有几种?
- javascript - 避免 React 功能组件中的代码重复
- mysql - Sequelize 和查询 MYSQL 字面量
- javascript - 如何在 React 中从父组件访问子组件中的变量?
- javascript - 只有当开发工具打开时,Chrome 才会在错误的位置触发拖动事件
- c# - 如何在 C# 中使用嵌套的 json 对象
- powershell - powershell catch 导出到 csv 不起作用
- reactjs - `npx install-peerdeps` 似乎不适用于纱线 3