Q:

Python program to find the maximum difference between tuple pairs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Finding the maximum difference between tuple pairs

We are given a list of tuples with integer values. We need to create a Python program to find the maximum difference between tuple pairs.

Input: 
tupList = [(5, 7), (2, 6), (1, 9), (1, 3)]

Output:
8

Explanation: 

Absolute difference of all tuples : 
(5, 7) = 2
(2, 6) = 4
(1, 9) = 8
(1, 3) = 2

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by creating a list with the absolute difference of all tuples of the list. And find the maximum value out of all these values.

# Python program to find the maximum difference 
# between tuple pairs

# Initializing and printing list
tupList = [(5, 7), (2, 6), (1, 9), (1, 3)]
print("The elements of list of tuples is " + str(tupList))

# Maximum difference between tuple pairs
maxTupDiff =max([abs(val2 - val1) for val1, val2 in tupList])

# Printing result
print("The Maximum absolute difference is " + str(maxTupDiff))

Output:

The elements of list of tuples is [(5, 7), (2, 6), (1, 9), (1, 3)]
The Maximum absolute difference is 8

Method 2:

Another approach is by using a lambda function to find the absolute difference of tuples of the list. The resultant is then passed to the max() function. And calculate the absolute difference.

# Initializing and printing list
tupList = [(5, 7), (2, 6), (1, 9), (1, 3)]
print("The elements of list of tuples is " + str(tupList))

# Maximum difference between tuple pairs
maxDiffTup = max(tupList, key = lambda tup: abs(tup[1] - tup[0]))

# Printing result
print("The Maximum absolute difference is " + str(maxDiffTup[1] - maxDiffTup[0]))

Output:

The elements of list of tuples is [(5, 7), (2, 6), (1, 9), (1, 3)]
The Maximum absolute difference is 8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now