首页 > 解决方案 > 在 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

标签: python

解决方案


您需要将 更改elifif。因为它是一个elif,一旦在 A 中找到一个项目,它就不会在 B 中检查,并且由于arrB 中存在的所有数字也在 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

推荐阅读