使用 Python 對陣列進行基於給定範圍的三路分割槽


給定一個數組和陣列的範圍 [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]

使用列表推導式對陣列進行基於給定範圍的三路分割槽

在本例中,我們將看到如何對陣列進行基於給定範圍的三路分割槽 -

示例

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 

更新於: 2022年8月12日

276 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告