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
Check if it is possible to create a polygon with given n sidess in Python
Suppose we have an array nums that contains the lengths of n sides. We have to check whether we can form a polygon with all of the given sides or not.
So, if the input is like nums = [3, 4, 5], then the output will be True because there are three sides and sum of any two sides is larger than the 3rd one. To solve this, we will use the polygon inequality theorem where the length of the longest side must be smaller than the sum of all other sides.
Algorithm
To solve this, we will follow these steps ?
- Sort the list nums in ascending order
- If the last element (longest side) is less than the sum of all other elements, then
- Return True
- Otherwise, return False
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
nums.sort()
if nums[-1] < sum(nums[:-1]):
return True
return False
nums = [3, 4, 5]
print(solve(nums))
The output of the above code is ?
True
Testing with Different Cases
Let's test our function with various examples to understand when polygon formation is possible ?
def solve(nums):
nums.sort()
if nums[-1] < sum(nums[:-1]):
return True
return False
# Test cases
test_cases = [
[3, 4, 5], # Valid triangle
[1, 2, 5], # Invalid - longest side too big
[2, 3, 4, 5], # Valid quadrilateral
[1, 1, 1, 3] # Invalid - longest side equals sum of others
]
for i, nums in enumerate(test_cases, 1):
result = solve(nums)
print(f"Test {i}: {nums} ? {result}")
The output of the above code is ?
Test 1: [3, 4, 5] ? True Test 2: [1, 2, 5] ? False Test 3: [2, 3, 4, 5] ? True Test 4: [1, 1, 1, 3] ? False
How It Works
The polygon inequality theorem states that for any polygon to exist, the sum of lengths of any (n-1) sides must be greater than the length of the remaining side. Since we sort the array, the last element is the longest side, so we only need to check if it's smaller than the sum of all other sides.
Conclusion
The polygon formation problem can be solved efficiently by sorting the sides and applying the polygon inequality theorem. The longest side must be strictly less than the sum of all other sides for a valid polygon.
