In: Computer Science
Name your functions countOnesLoop() and countOnesWhere() and submit your code in a file named countOnes.py.
Write a function that consists of a set of loops that run through an array and count the number of ones in it. Do the same thing using the where() function (use info(where) to find out how to use it) (in python)
Source Code:
import numpy as np          #it is used to implement array
def countOnesLoop(arr):
    count=0;
    for i in arr:
        if i==1:
            count+=1
    return count
def countOnesWhere(arr):
    for i in range(len(arr)):
        if arr[i]==1:
            print('1 found in index ',i)
def main():
    arr =np.array([1, 2, 3, 4, 1, 5, 6, 1, 7, 1])
    count=countOnesLoop(arr)
    print("Total no of 1 is ",count)
    countOnesWhere(arr)
    where=np.where(arr==1)          #where() method
    print('1 found in index ',where)
if __name__=="__main__":
    main()
Output:
