Python – Dual Element row with Maximum difference

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.

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:

1. Initialize the list of lists test_list with the input values.
2. Use reduce() with lambda to iterate through the list of lists and return the element with the maximum
3. absolute difference between its first and second values.
4. 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.`

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 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))`

Output
```The 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.

Previous
Next