使用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 教师闺蜜祝福语简短