5 Best Ways to Python Program to Calculate the Sum of the Right Diagonal of a Matrix

πŸ’‘ Problem Formulation:

Calculating the sum of the right diagonal (also known as the secondary diagonal) in a square matrix is a fundamental problem in programming and algorithms. Given a 2D square matrix (an array of arrays), the task is to find the sum of the elements on the diagonal that starts from the top right corner and ends at the bottom left corner. For example, in the matrix [[1,2,3], [4,5,6], [7,8,9]], the right diagonal elements are [3, 5, 7], and their sum is 15.

Method 1: Iterative Approach

This method uses a simple for loop to iterate through the matrix, and with each iteration, it selects the appropriate element from the current row that belongs to the right diagonal and adds it to the sum. Here’s an example:

def sum_right_diagonal(matrix):
    size = len(matrix)
    total = 0
    for i in range(size):
        total += matrix[i][size - i - 1]
    return total

# Example Matrix
matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]]

# Output
print(sum_right_diagonal(matrix))

Output: 15

In this snippet, the sum_right_diagonal function calculates the sum of the right diagonal elements. The loop iterates through each row, and for each row it calculates the index of the right diagonal element with size - i - 1, where i is the current zero-based row index and size is the dimension of the matrix. The elements obtained from each row are added to a total, which is then returned.

Method 2: Using List Comprehension

The list comprehension method in Python enables concise and readable code for calculating the sum of the right diagonal of a matrix. This is done in a single line by combining looping and indexing. Here’s an example:

def sum_right_diagonal_comp(matrix):
    return sum(matrix[i][len(matrix) - i - 1] for i in range(len(matrix)))

# Example Matrix
matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]]

# Output
print(sum_right_diagonal_comp(matrix))

Output: 15

The sum_right_diagonal_comp function makes use of Python’s list comprehension and the built-in sum function. It iterates over the indices of the rows and for each index, it computes len(matrix) - i - 1 to get the respective element from the right diagonal and sums up all such elements directly.

Method 3: Using zip and reversed Functions

By utilizing Python’s zip and reversed functions, we can pair each row of the matrix with its corresponding right diagonal element and then sum them up. Here’s an example:

def sum_right_diagonal_zip(matrix):
    return sum(row[-i-1] for i, row in enumerate(zip(*reversed(matrix))))

# Example Matrix
matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]]

# Output
print(sum_right_diagonal_zip(matrix))

Output: 15

In this code snippet, sum_right_diagonal_zip uses an iterator returned by enumerate(zip(*reversed(matrix))) which pairs each row of the reverersed matrix with its index, and for every pair, the appropriate right diagonal element is accessed using negative indexing row[-i-1] and summed up.

Method 4: Using NumPy Library

For those working with matrices in Python, the NumPy library provides efficient and convenient functions to perform matrix operations. Using NumPy’s flip and diagonal functions, calculating the sum of a matrix’s right diagonal becomes trivial. Here’s an example:

import numpy as np

def sum_right_diagonal_numpy(matrix):
    return np.flip(matrix, axis=1).diagonal().sum()

# Example Matrix
matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])

# Output
print(sum_right_diagonal_numpy(matrix))

Output: 15

The sum_right_diagonal_numpy function first flips the matrix horizontally with np.flip(matrix, axis=1). It then retrieves the primary diagonal of this flipped matrix with the diagonal method and calculates the sum of its elements using NumPy’s built-in sum method.

Bonus One-Liner Method 5: Lambda Function

Python’s lambda functions allow for writing small anonymous functions. This method leverages a lambda function to sum up the right diagonal in a one-liner expression. Here’s an example:

sum_right_diagonal_lambda = lambda m: sum(m[i][len(m) - i - 1] for i in range(len(m)))

# Example Matrix
matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]]

# Output
print(sum_right_diagonal_lambda(matrix))

Output: 15

Here, sum_right_diagonal_lambda is a lambda function that essentially performs the same operation as the list comprehension method, providing a compact solution for calculating the right diagonal sum.

Summary/Discussion

  • Method 1: Iterative Approach. Strengths: Easy to understand and implement. Weaknesses: Verbosity compared to other methods.
  • Method 2: Using List Comprehension. Strengths: Concise and Pythonic. Weaknesses: Can be less readable for those not familiar with list comprehensions.
  • Method 3: Using zip and reversed Functions. Strengths: Pythonic and makes good use of built-in functions. Weaknesses: May seem complex to those new to Python.
  • Method 4: Using NumPy Library. Strengths: Very efficient for large matrices and easy with NumPy functions. Weaknesses: Requires an external library, which may not be desirable for minimalistic or standalone scripts.
  • Bonus One-Liner Method 5: Lambda Function. Strengths: Extremely concise. Weaknesses: Could be harder to decode and debug due to its compact nature.