Home > Software engineering >  Why is my count variable not calculating correct number of True values from the list?
Why is my count variable not calculating correct number of True values from the list?

Time:11-26

I have a list values_count which contains boolean values True and False. I am trying to calculate number of True values present in the list. For example , for the list ltr=[False,True,True,True] I expect my answer to be 3 but my answer comes 0, the initial value of the count variable that I have declared. Below is my code.

    class Solution(object):

    def count_true(self, values_count=[]):

        am = 0
        for i in values_count:
            if values_count[i] == True:
                am   1
                return am
            else:
                pass


if __name__ == '__main__':
    p = Solution()
    ltr = [False, True, True, True]
    print(p.count_true(ltr))

CodePudding user response:

why not just

ltr = [False, True, True, True]
ltr.count(True)

CodePudding user response:

Actually, am 1 should be am = 1 and return am should be at the last line.

However, you can use my code below:

def count_true(self, values_count=[]):
    count = 0
    for value in values_count:
        if value:
            count  = 1
    return count

Output:

> 3
  • Related