Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking triangular inequality on list of lists in Python
The triangle inequality theorem states that the sum of any two sides of a triangle must be greater than the third side. In Python, we can check this property on a list of lists to identify which sublists can form valid triangles.
Using For Loop and Comparison
First, we sort each sublist to arrange sides in ascending order. Then we check if the sum of the two smaller sides is greater than the largest side ?
Example
triangle_data = [[3, 8, 3], [9, 8, 6], [2, 3, 8]]
# Sorting sublists to get sides in ascending order
for sides in triangle_data:
sides.sort()
# Check for triangular inequality
for sides in triangle_data:
if sides[0] + sides[1] > sides[2]:
print("Valid triangle:", sides)
else:
print("Invalid triangle:", sides)
Invalid triangle: [3, 3, 8] Valid triangle: [6, 8, 9] Invalid triangle: [2, 3, 8]
Using List Comprehension
We can use list comprehension to filter valid triangles in a more concise way ?
Example
triangle_data = [[3, 8, 3], [9, 8, 6], [2, 3, 8]]
# Sort each sublist
for sides in triangle_data:
sides.sort()
# Find valid triangles using list comprehension
valid_triangles = [sides for sides in triangle_data if sides[0] + sides[1] > sides[2]]
print("Valid triangles:")
for triangle in valid_triangles:
print(triangle)
Valid triangles: [6, 8, 9]
Complete Function Implementation
Here's a reusable function that checks triangle inequality without modifying the original data ?
def check_triangle_inequality(triangles):
"""Check which sublists satisfy triangle inequality"""
valid_triangles = []
for triangle in triangles:
# Create a sorted copy to avoid modifying original
sorted_sides = sorted(triangle)
a, b, c = sorted_sides[0], sorted_sides[1], sorted_sides[2]
if a + b > c:
valid_triangles.append(triangle)
return valid_triangles
# Test the function
triangle_data = [[3, 8, 3], [9, 8, 6], [5, 5, 5], [1, 2, 10]]
valid = check_triangle_inequality(triangle_data)
print("Original data:", triangle_data)
print("Valid triangles:", valid)
Original data: [[3, 8, 3], [9, 8, 6], [5, 5, 5], [1, 2, 10]] Valid triangles: [[9, 8, 6], [5, 5, 5]]
Comparison
| Method | Pros | Cons |
|---|---|---|
| For Loop | Easy to understand, step-by-step logic | More verbose code |
| List Comprehension | Concise, Pythonic syntax | Less readable for complex conditions |
| Function | Reusable, doesn't modify original data | Slightly more overhead |
Conclusion
Use list comprehension for simple triangle inequality checks. For more complex validation or when preserving original data is important, implement a dedicated function that creates sorted copies.
