Checking triangular inequality on list of lists in Python

PythonServer Side ProgrammingProgramming

The sum of two sides of a triangle is always greater than the third side. This is called triangle inequality. Python list of lists we will identify those sublists where the triangle inequality holds good.

With for and >

We will first get all the sublists sorted. Then for each sublist we will check if the if the sum of first two elements is greater than the third element.

Example

 Live Demo

Alist = [[3, 8, 3], [9, 8, 6]]
# Sorting sublist of list of list
for x in Alist:
   x.sort()
# Check for triangular inequality
for e in Alist:
   if e[0] + e[1] > e[2]:
      print("The sublist showing triangular inequality:",x)

Output

Running the above code gives us the following result −

The sublist showing triangular inequality:
[6, 8, 9]

With list comprehension

In this method, we also first sort the sublists and then use list comprehension to go through each of the sublists to check which one satisfies the triangle inequality.

Example

Alist = [[3, 8, 3], [9, 8, 6]]
# Sorting sublist of list of list
for x in Alist:
   x.sort()
# Check for triangular inequality
   if[(x, y, z) for x, y, z in Alist if (x + y) >= z]:
      print("The sublist showing triangular inequality: \n",x)

Output

Running the above code gives us the following result −

The sublist showing triangular inequality:
[6, 8, 9]
raja
Published on 20-May-2020 13:41:50
Advertisements