Python List Comprehension | Three way partitioning of an array around a given range

Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts.
1) All elements smaller than lowVal come first.
2) All elements in range lowVal to highVal come next.
3) All elements greater than highVal appear in the end.
The individual elements of three sets can appear in any order.

Examples:

Input: arr = [1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32]  
        lowVal = 14, highVal = 20
Output: arr = [1, 5, 4, 2, 3, 1, 14, 20, 20, 54, 87, 98, 32]

Input: arr = [1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32]  
       lowVal = 20, highVal = 20       
Output: arr = [1, 14, 5, 4, 2, 3, 1, 20, 20, 54, 87, 98, 32] 



We have existing solution for this problem please refer Three way partitioning of an array around a given range link. We can solve this problem quickly in python using List Comprehension. Approach is simple,

  1. Separate list in three parts, first one will contain elements less than lowVal, second will contain elements between lowVal and highVal, third will contain elements greater than highVal.
  2. Concatenate all three parts together.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Function for Three way partitioning of an
# array around a given range
  
def threeWay(input, lowVal, highVal):
  
# separate input list in three parts
     first = [ num for num in input if num<lowVal ]
     second = [ num for num in input if (num>=lowVal and num<=highVal) ]
     third = [ num for num in input if num>highVal ]
  
# concatenate all three parts
     print(first + second + third)
  
# Driver program
if __name__ == "__main__":
    input = [1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32]
    lowVal = 14
    highVal = 20
    threeWay(input, lowVal, highVal)

chevron_right


Output:

[1, 5, 4, 2, 3, 1, 14, 20, 20, 54, 87, 98, 32]


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.