python-3.x 给定一个方阵,计算其对角线之和的绝对差

wb1gzix0  于 2022-11-26  发布在  Python
关注(0)|答案(7)|浏览(138)
import numpy as np n=int(input())

R = n C = n p,s=0,0

print("Enter the entries in a single line (separated by space): ")

entries = list(map(int, input().split())) matrix = np.array(entries).reshape(R, C) print(matrix) for i in range(R): for j in range(C): if i==j: p=p+matrix[i][j] if i+j==n-1: s=s+matrix[i][j] s1=p-s print(s1)
axkjgtzd

axkjgtzd1#

r_sum=0
l_sum=0
for i in range(len(arr)):
    l_sum=l_sum+arr[i][i]
    r_sum=r_sum+arr[i][(len(arr)-1)-i]
return abs(l_sum - r_sum)

使用数组概念的#pyhton3

f8rj6qna

f8rj6qna2#

也许这会有所帮助:

c = np.array([[1,2,3],[4,5,6],[7,8,9]])
i,j = np.indices(c.shape)
sum1 = c[i==j].sum()
sum2 = c[i+j == len(c)-1].sum()
print(abs(sum1-sum2))
ds97pgxw

ds97pgxw3#

function absoluteDifference(arr){
    
    var sumDiagnoalOne=0
    var sumDiagnoalTwo=0
    for(var i=0; i<arr.length; i++){
    
        for(var j=i; j<arr.length; j++){
            sumDiagnoalOne+=arr[i][j]
            break
        }
    }
    var checkArray=[]
    arr.map(array=>checkArray.push(array.reverse()))
    for(var i=0; i<checkArray.length; i++){
    
        for(var j=i; j<checkArray.length; j++){
            sumDiagnoalTwo+=checkArray[i][j]
            break
        }
    }
    return Math.abs(sumDiagnoalOne- sumDiagnoalTwo)
}
atmip9wb

atmip9wb4#

包含

使用命名空间std;

int main() {
int n;
cin >> n;

int arr[n][n];

    long long int d1=0; //First Diagonal
    long long int d2=0; //Second Diagonal

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> arr[i][j];
            if (i == j) d1 += arr[i][j];
            if (i == n - j - 1) d2 += arr[i][j];
        }
    }

    cout << abs(d1 - d2) << endl; //Absolute difference of the sums across the 
diagonals
    return 0;
}
jq6vz3qz

jq6vz3qz5#

#!/bin/ruby

n = gets.strip.to_i
a = Array.new(n)
(0..n-1).each do |i|
    a[i] = gets.strip.split(' ').map(&:to_i)
end

d1 = 0
d2 = 0
(0..n-1).each do |i|
    d1 = d1 + a[i][i]
    d2 = d2 + a[-i-1][i]
end

print (d1-d2).abs
pxq42qpu

pxq42qpu6#

时间复杂度O(n)

function diagonalDifference(arr) {
    const size = arr.length;
    let lsum = 0;
    let rsum = 0;
    
    for(let i = 0; i < size; i ++){
        lsum += arr[i][i];
        
        rsum += arr[i][Math.abs(size - 1 - i)];          
    }
    return Math.abs(lsum - rsum);
}
rnmwe5a2

rnmwe5a27#

//sample array matrix 4x4
  const arr=[ [ 11, 2, 4 ,5], [ 4, 5, 6,4 ], [ 10, 8, -12,6 ],[ 10, 8, -12,6 ] ];
  
  function findMedian(arr) {
   const matrixType=arr.length
  const flat=arr.flat()
  let sumDiag1=0
  let sumDiag2=0  
  for(let i=0;i<matrixType;i++)
    {
      sumDiag1+=flat[i*(matrixType+1)]
      sumDiag2+=flat[(i+1)*(matrixType-1)]
    }
    
 const diff=Math.abs(sumDiag1-sumDiag2)
  return diff
}
console.log(findMedian(arr))

相关问题