We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3importmathimportosimportrandomimportreimportsysfromfunctoolsimportreduce## Complete the 'diagonalDifference' function below.## The function is expected to return an INTEGER.# The function accepts 2D_INTEGER_ARRAY arr as parameter.#defdiagonalDifference(arr):# Write your code heren=len(arr)tuple_list=[(i,j,arr[i][j])foriinrange(n)forjinrange(n)]sorted_tuples=sorted(tuple_list,key=lambdax:(x[0],x[1]))primary_diagonal=list(filter(lambdax:x[0]==x[1],sorted_tuples))secondary_diagonal=list(filter(lambdax:x[0]+x[1]==n-1,sorted_tuples))primary_diagonal_sum=reduce(lambdaacc,x:acc+x[2],primary_diagonal,0)secondary_diagonal_sum=reduce(lambdaacc,x:acc+x[2],secondary_diagonal,0)returnabs(primary_diagonal_sum-secondary_diagonal_sum)if__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')n=int(input().strip())arr=[]for_inrange(n):arr.append(list(map(int,input().rstrip().split())))result=diagonalDifference(arr)fptr.write(str(result)+'\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Diagonal Difference
You are viewing a single comment's thread. Return to all comments →
My Solution.