Three way partitioning of an array around a given range using Python

PythonProgrammingServer Side Programming

Given an array and the range of the array [startval, endval].Array is divided by three parts.

  • All elements smaller than startval come first.
  • All elements in range startval to endval come next.
  • All elements greater than endval appear in the end.

Examples

Input: A = [1, 14, 51, 12, 4, 2, 54, 20, 87, 98, 3, 1, 32]
startval = 14, endval = 54
Output: A = [1, 12, 4, 2, 3, 1, 14, 51, 20, 32,54, 87, 98]

Algorithm

Step1: First the list is divided into three parts, first part will contain elements less than startval, second part will contain elements between startval and endval and third part will contain elements greater than endval.
Step2: Concatenate all three parts together.

Example Code

def partition_array(input, lowVal, highVal):
   # Separate input list in three parts
   my_first = [ num for num in input if num<lowVal ]
   my_second = [ num for num in input if (num>=lowVal and num<=highVal) ]
   my_third = [ num for num in input if num>highVal ]
# concatenate all three parts
print(my_first + my_second + my_third)
# Driver program
if __name__ == "__main__":
   my_input = [10, 140, 50, 200, 40, 20, 540, 200, 870, 980, 30, 10, 320]
   my_lowVal = 140
   my_highVal = 200
   partition_array(my_input, my_lowVal, my_highVal)

Output

[10, 50, 40, 20, 30, 10, 140, 200, 200, 540, 870, 980, 320]
raja
Published on 23-Nov-2018 12:23:21
Advertisements