Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to extract rows with common difference elements
When it is required to extract rows with common difference elements (arithmetic progression), we can iterate through each row and check if consecutive elements have the same difference. A flag value is used to track whether a row maintains constant difference throughout.
Understanding Common Difference
A sequence has common difference when the difference between consecutive elements remains constant. For example, in [11, 12, 13], the difference is always 1.
Example
Below is a demonstration of extracting rows with common difference ?
data_list = [[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]]
print("The list is :")
print(data_list)
result = []
for row in data_list:
temp = True
for index in range(0, len(row) - 1):
if row[index + 1] - row[index] != row[1] - row[0]:
temp = False
break
if temp:
result.append(row)
print("The resultant list is :")
print(result)
Output
The list is : [[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]] The resultant list is : [[11, 12, 13]]
How It Works
The algorithm works as follows ?
For each row, calculate the initial difference between first two elements
Check if all consecutive pairs maintain this same difference
If any pair has a different difference, mark the row as invalid
Only rows with consistent differences are added to the result
Alternative Approach Using List Comprehension
A more concise solution using list comprehension ?
data_list = [[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]]
result = [row for row in data_list
if all(row[i+1] - row[i] == row[1] - row[0]
for i in range(len(row) - 1))]
print("Original list:", data_list)
print("Rows with common difference:", result)
Original list: [[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]] Rows with common difference: [[11, 12, 13]]
Conclusion
Use iteration with a flag variable for readable code, or list comprehension with all() for a more concise approach. Both methods effectively identify rows where consecutive elements maintain constant differences.
