使用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 婆婆高寿祝福语大全简短