"Python exercise 028" to find the sum of diagonal elements of a 3*3 matrix
-----------------------------------------------------
This solution is solved, but always feel that the code is too verbose. Matrix This thing, there should be a very readily available method can be calculated directly to ... The verbose code is as follows:
str = input (' Please enter 9 digits separated by a space to form the 3*3 matrix: ') n = [Int (i) for I in Str.split (")] #获取9个数字mx = [] #存储矩阵for i in range (3): C5/>MT = [] #收集矩阵中每行的数字列表 for J in Range (3): mt.append (n[i*3 + j]) Mx.append (MT) #每行数字存储进mx列表 Print (mt) sum1 = 0sum2 = 0for i in range (3): sum1 + = Mx[i][i] sum2 + = Mx[2-i][i]print (the sum of the diagonal 3 elements of the direction is:%s '% s UM1) print (the sum of the 3 elements in the direction diagonal:%s '% sum2)
The output results are as follows:
Please enter 9 digits separated by a space to form the 3*3 matrix: 7 9 6 5 4 8 6 7 3
[7, 9, 6]
[5, 4, 8]
[6, 7, 3]
The sum of the diagonal 3 elements of the direction is: 14
/Direction Diagonal 3 element sum is: 16
As long as the code changes slightly, you can accept any n*n matrix calculation, and the number of input errors, you can also prompt for re-input. The following code is changed:
Import Matherr = Truewhile err: str = input (' Please enter a n**2 number, separated by a space to form a n*n matrix: ') n = [Int (i) for I in Str.split (")]
#获取9个数字 t = Math.floor (MATH.SQRT (len (n))) if T = = math.sqrt (len (n)) and T! = 1: err = False else: p Rint (' The number you have entered is incorrect, please try again. ') mx = [] #存储矩阵for i in range (t): MT = [] #收集矩阵中每行的数字列表 for J in range (T): mt.append (N[i*t + j])
mx.append (MT) #每行数字存储进mx列表 Print (mt) sum1 = 0sum2 = 0for i in range (t): sum1 + = Mx[i][i] sum2 + = mx [T-1-i] [I]print (the sum of the diagonal elements of the direction is:%s '% sum1) print (the sum of the diagonal elements of the direction is:%s '% sum2)
The output results are as follows:
Please enter a n**2 number, separated by a space, to form a matrix of N*n: 8 7 5 4 3 5 6 7 4 5 3 4 2 9 8 7 5 8 9 6 5 2 3 2 6
[8, 7, 5, 4, 3]
[5, 6, 7, 4, 5]
[3, 4, 2, 9, 8]
[7, 5, 8, 9, 6]
[5, 2, 3, 2, 6]
The sum of the diagonal elements in the direction is: 31
/direction diagonal element sum is: 19
Although it worked, I still firmly believe that Python must have prepared a function or method that can easily calculate the matrix. Let me have a good time to search, and then update.
++++++++++++++++++++++++++++++++++++++
Source: Programming Language Introduction Classic 100 Cases "Python Edition"
Python Exercise 028: Finding the sum of diagonal numbers of 3*3 matrices