Python - Dual Element row with Maximum difference
Last Updated :
01 Jun, 2023
Sometimes, while working with Python Matrix, we can have Matrix with its elements to be rows with just two elements and we may desire to get row with elements having maximum difference. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way in which this task can be performed. In this we iterate for each row and compute maximum and store row with larger difference each time while iteration.
Python3
# Python3 code to demonstrate
# Dual Element row with Maximum difference
# using loop
# Initializing list
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# Dual Element row with Maximum difference
# using loop
max_till = -float('inf')
res = []
for sub in test_list:
if abs(sub[0] - sub[1]) > max_till:
max_till = abs(sub[0] - sub[1])
res = sub
# printing result
print ("The maximum difference row is : " + str(res))
Output : The original list is : [[5, 10], [1, 3], [4, 11], [1, 2]]
The maximum difference row is : [4, 11]
Method #2 : Using max() + lambda + list comprehension The combination of above functionalities can be used to perform this task. In this, we perform the task of getting maximum using max() and lambda function and list comprehension is used to perform task of iteration.
Python3
# Python3 code to demonstrate
# Dual Element row with Maximum difference
# using max() + lambda + list comprehension
# Initializing list
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# Dual Element row with Maximum difference
# using max() + lambda + list comprehension
res = max(test_list, key = lambda ele: abs(ele[0] - ele[1]))
# printing result
print ("The maximum difference row is : " + str(res))
Output : The original list is : [[5, 10], [1, 3], [4, 11], [1, 2]]
The maximum difference row is : [4, 11]
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a list with m * n keys and a list of m * n elements
Method #3 : Using Numpy Library
This method makes use of numpy library and its functions numpy.amax() and numpy.abs() to perform the task. The numpy.amax() function returns the maximum value along a given axis.
Note: Install numpy module using command "pip install numpy"
Python3
#Python3 code to demonstrate
#Dual Element row with Maximum difference
#using Numpy Library
#importing numpy library
import numpy as np
#Initializing list
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
#printing original list
print("The original list is : " + str(test_list))
#Dual Element row with Maximum difference
#using Numpy Library
res = np.array(test_list)
res = res[np.abs(res[:,0]-res[:,1]).argmax()]
#printing result
print ("The maximum difference row is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output:
The original list is : [[5, 10], [1, 3], [4, 11], [1, 2]]
The maximum difference row is : [ 4 11]
Time complexity: O(n), where n is the number of rows in the matrix.
Space complexity: O(1)
In this approach, the numpy library is used to perform the task and it is more efficient compared to the previous two methods as it makes use of optimized built-in functions for performing the task.
Method #4:using reduce() and lambda:
- Initialize the list of lists test_list with the input values.
- Use reduce() with lambda to iterate through the list of lists and return the element with the maximum
- absolute difference between its first and second values.
- Print the maximum difference row obtained in step 2.
Python3
# Python3 code to demonstrate
# Dual Element row with Maximum difference
# using reduce() + lambda
# importing functools module
from functools import reduce
# Initializing list
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# Dual Element row with Maximum difference
# using reduce() + lambda
max_row = reduce(lambda x, y: x if abs(x[0] - x[1]) > abs(y[0] - y[1]) else y, test_list)
# printing result
print("The maximum difference row is: ", max_row)
#This code is contributed by Jyothi Pinjala.
OutputThe original list is : [[5, 10], [1, 3], [4, 11], [1, 2]]
The maximum difference row is: [4, 11]
Time Complexity: O(n), where n is the number of elements in the list of lists.
Auxiliary Space: O(1), since the maximum difference row is a constant-size list of length 2.has context menu
Method #5: Using the pandas library
Import the pandas library
Convert the test_list to a DataFrame using pd.DataFrame
Create a new column in the DataFrame by taking the absolute difference between the two elements in each row using abs(df[0] - df[1])
Find the index of the row with the maximum value in this column using idxmax()
Retrieve the row using .iloc[] and convert it to a list using .tolist()
Python3
import pandas as pd
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
df = pd.DataFrame(test_list)
max_row = df.iloc[df[0].sub(df[1]).abs().idxmax()].tolist()
print("The maximum difference row is: ", max_row)
OUTPUT :
The maximum difference row is: [4, 11]
Time complexity: O(n), where n is the number of rows in test_list
Auxiliary space: O(n), for creating the DataFrame
Method #6: Using list sorting
Python3
# Initializing list
test_list = [[5, 10], [1, 3], [4, 11], [1, 2]]
# Printing original list
print("The original list is: " + str(test_list))
# Sorting the list based on the absolute difference
test_list.sort(key=lambda x: abs(x[0] - x[1]), reverse=True)
# The maximum difference row is the first element in the sorted list
res = test_list[0]
# Printing result
print("The maximum difference row is: " + str(res))
OutputThe original list is: [[5, 10], [1, 3], [4, 11], [1, 2]]
The maximum difference row is: [4, 11]
Time complexity: The time complexity of this method is O(n log n), where n is the number of sublists in the test_list. Sorting the list takes O(n log n) time.
Auxiliary space: This method has an auxiliary space complexity of O(1) because it uses a constant amount of additional space for sorting the list in-place.
Similar Reads
Python - Row with Minimum difference in extreme values
Given a Matrix, extract the rows with a minimum difference in extreme values. Examples: Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]] Output : [[1, 4, 6], [5, 0]] Explanation : 6 - 1 = 5, 5 - 0 = 5, is minimum difference between extreme values. Input : test_list = [[4, 10, 18], [5, 0
4 min read
Python - Element wise Matrix Difference
Given two Matrixes, the task is to write a Python program to perform element-wise difference. Examples: Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]] Explanation : 6 - 2 = 4, 4 - 4 = 0, 6 - 5 = 1. And
3 min read
Python - Row with Maximum Record Element
Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [
7 min read
Python | Maximum Difference in String
Sometimes, we might have a problem in which we require to get the maximum difference of 2 numbers from Strings but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Letâs discuss certain ways in which this problem can be solved. Met
4 min read
Python | Record Point with Minimum difference
Sometimes, while working with data, we might have a problem in which we need to find minimum difference between available pairs in list. This can be application to many problems in mathematics domain. Letâs discuss certain ways in which this task can be performed.Method #1 : Using min() + list compr
2 min read
Python program to extract rows with common difference elements
Given a Matrix, extract rows with AP sequence. Input : test_list = [[4, 7, 10], [8, 10, 12], [10, 11, 13], [6, 8, 10]] Output : [[4, 7, 10], [8, 10, 12], [6, 8, 10]] Explanation : 3, 4, and 2 are common difference in AP. Input : test_list = [[4, 7, 10], [8, 10, 13], [10, 11, 13], [6, 8, 10]] Output
3 min read
Python | Maximum distance between elements
Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let's discuss certain way in which this task can be performed. Method 1:
6 min read
Python | Find Maximum difference pair
Sometimes, we need to find the specific problem of getting the pair which yields the maximum difference, this can be solved by sorting and getting the first and last elements of the list. But in some case, we don't with to change the ordering of list and perform some operation in a similar list with
5 min read
Python - Maximum difference across lists
Given two lists, the task is to write a Python program to find maximum difference among like index elements. Examples: Input : test_list1 = [3, 4, 2, 1, 7], test_list2 = [6, 2, 1, 9, 1]Output : 8Explanation : 9 - 1 = 8 is maximum difference across lists in same index. Input : test_list1 = [3, 4, 2,
4 min read
Python Program to Find a pair with the given difference
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
4 min read