-3

Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

For example,

[True,  True,  True,  False,
  True,  True,  True,  True ,
  True,  False, True,  False,
  True,  False, False, True ,
  True,  True,  True,  True ,
  False, False, True,  True]

The correct answer would be 17.

This is what I tried:

def count_sheeps(sheep):
    total = 0
    for i in sheep:
        if i == 'True':
            total += i
        else:
            return None

This code throws up an error saying that None should equal 17.

Saeed
  • 3,255
  • 4
  • 17
  • 36
i_am_pro
  • 1
  • 1
  • 2
    Drop the `else` part, you don't need to do anything if `i` is false. When the `for` loop is finished, `return total`. – Tony Jan 08 '23 at 06:03
  • Also need to compare to `i is True`, not `i == 'True'`. But you can do it much more elegantly: `sheeps.count(True)`. – Zac Anger Jan 08 '23 at 06:04
  • `True` is also `1`. You could just `sum(sheep)`. – tdelaney Jan 08 '23 at 06:08
  • Wait a second, is that `True` or `"True"`? Make sure this is a working example. – tdelaney Jan 08 '23 at 06:09
  • Does this answer your question? [Counting the number of True Booleans in a Python List](https://stackoverflow.com/questions/12765833/counting-the-number-of-true-booleans-in-a-python-list) – buran Jan 08 '23 at 07:08

3 Answers3

1

The problem is that you are comparing bool with str.

You can use if i:.

BTW, If you want to count the Trues in your list, you can use sum as True is 1:

sum([True, False, True, True])
>> 3
Amin
  • 2,605
  • 2
  • 7
  • 15
1

The problem is "True" is a string. You can not compare it with a bool type:

var1 = True
var2 = "True"

print(var1, type(var1)) # True <class 'bool'>
print(var2, type(var2)) # True <class 'str'>

So you could say: if i is True. Or because you're only dealing with True and False, you could say if i. (Don't forget to return the total from your function.

lst = [True, False, True]

def count_sheeps(sheep):
    total = 0
    for i in sheep:
        if i:
            total += i
    return total

print(count_sheeps(lst))

That explained your problem, but list class has implemented .count method which can count the item you pass it:

lst = ["a", "b", "a"]
print(lst.count("a"))

Moreover, bool is a subclass of int, True is considered 1 and False is considered 0. So you could also use sum():

def count_sheeps(sheep: list[bool]):
    return sum(sheep)
S.B
  • 13,077
  • 10
  • 22
  • 49
0
def count_sheep(array):
    return array.count("sheep")

example:

animals = ["sheep", "cow", "sheep", "chicken", "sheep"]
print(count_sheep(animals))  # Output: 3
S.B
  • 13,077
  • 10
  • 22
  • 49