Python - Rows intersection with K

Python - Rows intersection with K

Let's tackle the problem of finding the rows in a 2D list (or matrix) that intersect with a given list K.

Problem Statement:

Given a matrix (2D list) and a list K, find all rows in the matrix that have an intersection with K. An intersection means that there's at least one element common between the row and K.

Example:

For the matrix:

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

And the list: K=[4,7]

The rows that intersect with K are:

[ [4, 5, 6], [7, 8, 9], [1, 4, 7] ] 

Tutorial:

1. Using List Comprehension:

List comprehension is a concise method to create lists. We can use it to iterate through the rows of the matrix and filter the ones that intersect with K.

def rows_intersection(matrix, K): return [row for row in matrix if set(row) & set(K)] # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7] ] K = [4, 7] print(rows_intersection(matrix, K)) # Output: [[4, 5, 6], [7, 8, 9], [1, 4, 7]] 

Explanation:

  • We convert each row and the list K into sets. The operation set(row) & set(K) computes the intersection of the two sets. If the intersection is non-empty, then there's a common element between the row and K, and we include that row in our result.

2. Using a Loop:

For those who prefer an explicit loop, the same operation can be expanded as:

def rows_intersection(matrix, K): result = [] for row in matrix: if set(row) & set(K): result.append(row) return result # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7] ] K = [4, 7] print(rows_intersection(matrix, K)) # Output: [[4, 5, 6], [7, 8, 9], [1, 4, 7]] 

Conclusion:

Identifying rows in a matrix that intersect with a given list K is quite straightforward in Python. By leveraging set operations, we can efficiently determine intersections and filter the matrix rows accordingly.


More Tags

jtextcomponent uiwebview line-intersection delete-directory event-delegation eventemitter aws-cloudformation task punctuation static-analysis

More Programming Guides

Other Guides

More Programming Examples