python - 在 for 循环中负递增不能提供正确的答案
问题描述
给定以下代码,它对集合 A 计数为正,对集合 B 计数为负。集合 A 按预期工作,但集合 B 给出0
答案而不是-2
. 这是为什么 ?
arr = [1,3,2,12]
A = set([1,3,5])
B = set([1,3,5])
def func(arr,A,B):
countA = 0
countB = 0
for i in arr:
if i in A:
countA += 1
elif i in B:
countB -= 1
return countA
返回 2。但是....
arr = [1,3,2,12]
A = set([1,3,5])
B = set([1,3,5])
def func(arr,A,B):
countA = 0
countB = 0
for i in arr:
if i in A:
countA += 1
elif i in B:
countB -= 1
return countB
返回 0
解决方案
您需要将 更改elif
为if
。因为它是一个elif
,一旦在 A 中找到一个项目,它就不会在 B 中检查,并且由于arr
B 中存在的所有数字也在 A 中,所以你得到 0。只是:
def func(arr,A,B):
countA = 0
countB = 0
for i in arr:
if i in A:
countA += 1
if i in B:
countB -= 1
return countA, countB
推荐阅读
- typescript - 如何使用 Typescript 在 Material UI 中扩展调色板
- swift - 有没有办法让 SwiftUI 文本标签在显示计时器时不会轻微移动?
- javascript - FindDomNode 弃用警告,尽管使用了 ref
- java - 如何在不损坏的情况下将图像从 java 套接字服务器发送到导航器?
- laravel - 无法打开 laravel.log - ec2 Aws 中的权限错误
- u-boot - 错误:所选处理器不支持请求的专用寄存器
- swift - 检查 URL 是视频 URL 还是 PHOTO URL
- python - Template Does not exsist-heroku django
- scala - 类型参数 [T] 不符合方法产品的类型参数边界 [T <: Product]
- asp.net-mvc - How to use asp.net core 3.0 identity (Register & SignIn) for multiple UserName/Email with Different CompanyIDs