
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Triangular Inequality on List of Lists in Python
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
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]
Advertisements