Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).

The trace of an n-by-n square matrix **A** is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of **A**.

A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.

For example, the following code...
```ruby,python
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
represents the matrix
```
|1 2 3|
|4 5 6|
|7 8 9|
```
which has a trace of `1 + 5 + 9 = 15`.

You can read more about the trace of a matrix at these sources:

 * http://en.wikipedia.org/wiki/Trace_(linear_algebra)
 * http://mathworld.wolfram.com/MatrixTrace.html

~~~if:ruby
Note: The `Matrix` class is disabled.
~~~
~~~if:python
Note: `Numpy` is disabled.
~~~

Source: codewars | Difficulty: EASY
Tags: Matrices

Mathematics

Starter code: def trace(matrix):
	

Solutions:
def trace(matrix):
	if not matrix or len(matrix) != len(matrix[0]):
		return None
	return sum((matrix[i][i] for i in range(len(matrix))))


def trace(matrix):
	if matrix and set(map(len, matrix)) == {len(matrix)}:
		return sum((matrix[x][x] for x in range(len(matrix))))


trace = lambda m: sum((m[i][i] for i in range(len(m)))) if m and len(m) == len(m[0]) else None


def trace(matrix):
	if matrix and {len(matrix)} == {len(m) for m in matrix}:
		return sum((matrix[i][i] for i in range(len(matrix))))


def trace(mx):
	return None if not mx or len(mx) != len(mx[0]) else sum((mx[i][i] for i in range(len(mx))))


def trace(matrix):
	matrixLen = len(matrix)
	if matrixLen == 0:
		return None
	matrixElemsLens = [len(i) for i in matrix]
	for i in matrixElemsLens:
		if i != matrixLen:
			return None
	totalTrace = 0
	currentElem = 0
	for row in matrix:
		totalTrace += row[currentElem]
		currentElem += 1
	return totalTrace


def trace(matrix):
	return sum((matrix[i][i] for i in range(len(matrix)))) if len(matrix) > 0 and len(matrix[0]) == len(matrix) else None


def trace(matrix):
	if matrix and len(matrix) == len(matrix[0]):
		return sum((row[i] for (i, row) in enumerate(matrix)))


def trace(matrix):
	size = len(matrix)
	if not matrix or any((len(row) != size for row in matrix)):
		return None
	return sum((matrix[i][i] for i in range(size)))


trace = lambda m: None if not m or len(m) != len(m[0]) else sum([m[i][i] for i in range(len(m))])