使用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 生女孩红包简短祝福语