Python program to extract rows with common difference elements

Python program to extract rows with common difference elements

Creating a tutorial to write a Python program that extracts rows from a 2D list (or matrix) where elements have a common difference:

Objective: Given a 2D list (matrix), we want to extract the rows where the elements of each row have a common difference.

Example:

Matrix: [ [1, 3, 5, 7], [10, 12, 14, 16], [2, 6, 10, 14], [5, 7, 9, 11] ] Output: [ [1, 3, 5, 7], [10, 12, 14, 16], [5, 7, 9, 11] ] 

Step-by-step Solution:

Step 1: Define the input matrix.

matrix = [ [1, 3, 5, 7], [10, 12, 14, 16], [2, 6, 10, 14], [5, 7, 9, 11] ] 

Step 2: Create a function to check if a list has elements with a common difference.

def has_common_difference(lst): diff = lst[1] - lst[0] for i in range(1, len(lst)): if lst[i] - lst[i - 1] != diff: return False return True 

Step 3: Use the function to filter out rows with a common difference.

result = [row for row in matrix if has_common_difference(row)] 

Step 4: Print the resulting rows.

print(result) 

Complete Program:

def has_common_difference(lst): diff = lst[1] - lst[0] for i in range(1, len(lst)): if lst[i] - lst[i - 1] != diff: return False return True # Define the input matrix matrix = [ [1, 3, 5, 7], [10, 12, 14, 16], [2, 6, 10, 14], [5, 7, 9, 11] ] # Extract rows with a common difference result = [row for row in matrix if has_common_difference(row)] # Print the result print(result) 

Output:

[ [1, 3, 5, 7], [10, 12, 14, 16], [5, 7, 9, 11] ] 

This tutorial demonstrates how to extract rows from a matrix that have elements with a common difference. The has_common_difference function checks if all adjacent elements in a list have the same difference, and this is used to filter the rows of the input matrix.


More Tags

grails-orm angular-cli-v6 memory-leak-detector roi zip4j knockout-2.0 react-boilerplate assembly color-picker dynamic-sql

More Programming Guides

Other Guides

More Programming Examples