Check if it is possible to rearrange rectangles in a non-ascending order of breadths in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of rectangles represented using its length and breadth. We can rotate any rectangle by 90 degrees so after rotating, the breadth will become length and vice-versa. We have to check whether we can sort the rectangles in non-increasing order of breadth.

So, if the input is like rects = [[4, 5], [5, 7], [4, 6]], then the output will be True as the breadths are [5,7,6] now if we rotate last two rectangles then breadths will be [5,5,4] which is in non-increasing way.

To solve this, we will follow these steps −

  • m := 99999
  • for i in range 0 to size of rect, do
    • if maximum of length and breadth of ith rectangle <= m, then
      • m := maximum of length and breadth of ith rectangle
    • otherwise when minimum of length and breadth of ith rectangle <= m
      • m := minimum of length and breadth of ith rectangle
    • otherwise,
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(rect):
   m = 99999
   for i in range(len(rect)):
      if max(rect[i][0], rect[i][1]) <= m:
         m = max(rect[i][0], rect[i][1])
      elif min(rect[i][0], rect[i][1]) <= m:
         m = min(rect[i][0], rect[i][1])
      else:
         return False
   return True
rects = [[4, 5], [5, 7], [4, 6]]
print(solve(rects))

Input

[[4, 5], [5, 7], [4, 6]]

Output

True
raja
Published on 18-Jan-2021 13:31:43
Advertisements