Check if given four integers (or sides) make rectangle in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of four sides, we have to check whether these four sides are forming a rectangle or not.

So, if the input is like sides = [10, 30, 30, 10], then the output will be True as there are pair of sides 10 and 30.

To solve this, we will follow these steps −

  • if all values of sides are same, then
    • return True
  • otherwise when sides[0] is same as sides[1] and sides[2] is same as sides[3], then
    • return True
  • otherwise when sides[0] is same as sides[3] and sides[2] is same as sides[1], then
    • return True
  • otherwise when sides[0] is same as sides[2] and sides[3] is same as sides[1], then
    • return True
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(sides):
   if sides[0] == sides[1] == sides[2] == sides[3]:
      return True
   elif sides[0] == sides[1] and sides[2] == sides[3]:
      return True
   elif sides[0] == sides[3] and sides[2] == sides[1]:
      return True
   elif sides[0] == sides[2] and sides[3] == sides[1]:
      return True
   return False
sides = [10, 30, 30, 10]
print(solve(sides))

Input

[10, 30, 30, 10]

Output

True
raja
Published on 18-Jan-2021 12:45:40
Advertisements