Home > katas > Counting sheep... (8kyu) [Python]

Counting sheep... (8kyu) [Python]


Chek kata on Codewars

Description:

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.

Hint: Don't forget to check for bad values like null/undefined

Solution 1

Let's start with loop solutions.

def count_sheeps(arrayOfSheeps):
    amount = 0
    for sheep in arrayOfSheeps:
        if (sheep == True):
            amount += 1
    return amount

Solution 2

Let's solve it with count().

def count_sheeps(arrayOfSheeps):
    return arrayOfSheeps.count(True)

count() is an inbuilt function in Python that returns count of how many times a given object occurs in list.

Solution 3

Let's solve it with List Comprehension.

def count_sheeps(arrayOfSheeps):
    return len([sheep for sheep in arrayOfSheeps if sheep])

Solution 4

Let's solve it with Sum & Filter.

def count_sheeps(arrayOfSheeps):
    return sum(filter(lambda sheep: sheep == True, arrayOfSheeps))

Solution 5

Let's solve it with reduce().

def count_sheeps(arrayOfSheeps): return reduce(
    lambda acc, cur: acc + 1 if cur == True else acc, arrayOfSheeps)
© 2021, Andrew Losseff