In: Computer Science
Write a function hitRate(A, B) to return the percentage of elements in array A that match the elements with the same index in array B. A and B are 1darrays or 2darrays of the same shape. Sample: if X = np.array([1, 3, 5, 8]); Y = np.array([2, 1, 3, 8]), then hitRate(X, Y) returns 0.25. in python program
Please up vote ,comment if any query . Thanks for Question . Be safe .
Note : check attached image for output and indentation . code compiled and tested in spyder python 3.
Program Plan :
If Array is 1 dimensional :
Program :
import numpy #import numpy array
#function takes two numpy array A and B
#both are 2d or 1d
def hitRate(A,B):
dim=A.ndim #get number of dimensional
count=0 #count number of element
same
length=0 #total element
if dim==2: #if array is 2D
#run loop for first to
last column
for i in
range(len(A)):
for j in range(len(A[i])): #run a loop from 0 to last column
element
length+=1 #increment number of elements
if A[i][j]==B[i][j]: #if both element are same
count+=1 #increment count
elif dim==1:#if array is 1D
length=len(A)#get length
of array
#from 1st to last
element
for i in
range(len(A)):
if A[i]==B[i]: #if element same
count+=1 #increment count
#calculate percentage
percentage=count*100/length
return percentage #return
if __name__=="__main__":
arr = numpy.array([[1, 3, 5,8],[3,4,5,8]])
arr1 =numpy.array([[3,4,5,2],[1, 3, 5,8]])
print("Hit percentage : ",hitRate(arr,
arr1))
arr2 = numpy.array([1, 3, 5,8])
arr3 =numpy.array([3,4,5,8])
print("Hit Percentage : ",hitRate(arr2,
arr3))
Output :
Program :
Please up vote ,comment if any query .