使用 Python 对给定范围内的数组进行三向分区
programmingpythonserver side programming
给定一个数组和数组的范围 [startval, endval]。数组被分为三部分。
所有小于 startval 的元素都排在最前面。
所有在 startval 到 endval 范围内的元素都排在后面。
所有大于 endval 的元素都排在最后。
假设我们有以下输入 −
A = [1, 14, 51, 12, 4, 2, 54, 20, 87, 98, 3, 1, 32] startval = 14, endval = 54
输出应为 −
A = [1, 12, 4, 2, 3, 1, 14, 51, 20, 32,54, 87, 98]
使用 List Comprehension 对给定范围的数组进行三向分区
在此示例中,我们将看到如何对给定范围的数组进行三向分区 −
示例
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 the 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)
输出
[10, 50, 40, 20, 30, 10, 140, 200, 200, 540, 870, 980, 320]
使用 while 循环围绕给定范围对数组进行三向分区
在此示例中,我们将看到如何使用 while 循环围绕给定范围对数组进行三向分区 −
示例
def partitionFunc(my_input, n, lowVal, highVal): begn = 0 end = n - 1 i = 0 # Looping while i <= end: if my_input[i] < lowVal: my_input[i], my_input[begn] = my_input[begn], my_input[i] i += 1 begn += 1 elif my_input[i] > highVal: my_input[i], my_input[end] = my_input[end], my_input[i] end -= 1 else: i+=1 # Driver code if __name__ == "__main__": my_input = [1, 14, 51, 12, 4, 2, 54, 20, 87, 98, 3, 1, 32] n = len(my_input) partitionFunc(my_input, n, 14, 54) for i in range(n): print(my_input[i], end = " ")
输出
1 12 4 2 1 3 54 20 32 51 14 98 87