题目:
Consider an array 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
解题办法:
def count_sheeps(arrayOfSheeps): sum = 0 for x in arrayOfSheeps: if x: sum += 1 return sum
其他解法:
def count_sheeps(arrayOfSheeps): return arrayOfSheeps.count(True)
知识点:
1、计算s数量可以使用l.count(s)