python - 这个功能是合乎逻辑的还是我想多了?查找偶数的循环错误
问题描述
哪个代码段应该替换函数 hasEvenNumber 中的语句pass,如果 n 包含偶数则返回 True,否则返回 False?
def hasEvenNumber(n):
for i in n:
pass # Replace this section with below options
return result
这是一道真正的大学考试题。我发现它的结构很糟糕,因为我的同学也是新的,没有人敢说出来,害怕出丑。
首先没有给出n,而是判断在for循环中会用到n。因此,n 将是一个可迭代的。我认为这 4 个选项都不适用,但如果我错了,请告诉我。
选项1:
if i % 2 == 0:
result = True
else:
result = False
这仅在可迭代项仅包含 1 项时才有效,例如 [1,2,1] 将不起作用,因为 2 作为偶数应该返回 true 的结果将在循环继续进行下一次迭代时被替换。
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] True
[2] True
选项 2:
if i % 2 == 0:
result = True
break
else:
result = False
break
比上面更糟糕的是,这只会迭代第一个项目并且无论如何都会中断。
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] False # Wrong, should be true
[2] True
选项 3:
if i % 2 == 0:
result = True
break
如果没有找到偶数,函数将出现运行时错误,变量结果将不会被赋值。
[1,2,1,1] True
[1,1,1,1] Runtime Error
[2] True
[1] Runtime Error
选项 4:
if i % 2 != 0:
result = False
break
同上,运行时错误。如果都是偶数,则不会分配任何变量。
就个人而言,作为检查 n 是否包含偶数的问题。我会写这样的东西。
# Break and exit loop once even number is found. Otherwise continue.
if i % 2 == 0:
result = True
break
else:
result = False
不幸的是,这不是一个选择。抱歉,如果这是张贴此错误的地方,但任何建议将不胜感激,并且可能会改变我们当前学校队列的命运。
解决方案
是的,你是对的,而且有点想多了。
第三个选项是正确的,这里假设一开始result
就设置为False
。
此外,您的解决方案可以通过result = False
在开始时声明一次来优化,然后您可以else
完全消除该块。
推荐阅读
- powershell - 在 powershell 中复制脚本时遇到问题
- azure-devops - 将图形文件上传到 devops 以在 markdown 中使用
- c# - 使用身份服务器 4 使用有效的访问令牌获取 401 Unauthorized
- r - 在 R 中的 log10 scale_y_continuous 中设置 ylim
- php - 如何在 PHP 箭头函数中编写多个表达式
- python - 在 numpy 数组中绘制具有 RGB 值的图像列表
- list - 如何逐个元素地遍历列表
- python - 我不能在 python 中使用 open()
- python - 对变量在 python 中的工作方式感到困惑
- f# - 在 Paket 依赖组之间共享版本?