使用Python在给定范围内对数组进行三向分区
给定一个数组和数组的范围[startval,endval].Array被三部分划分。
所有小于startval的元素排在第一位。
接下来是startval到endval范围内的所有元素。
所有大于endval的元素都显示在末尾。
例子
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]
算法
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.
范例程式码
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)
输出结果
[10, 50, 40, 20, 30, 10, 140, 200, 200, 540, 870, 980, 320]
热门推荐
10 送离职同事简短祝福语
11 新年给妈妈简短祝福语
12 新娘对伴娘祝福语简短
13 幸福卡片祝福语英文简短
14 婚礼仪式祝福语简短
15 送菜的祝福语简短霸气
16 给司机老师祝福语简短
17 朋友明天手术祝福语简短
18 初八的祝福语简短