标签:测试 app sort style while -- 排序 描述 数组
题目描述:
1 def sortArray(A): 2 odd = [] 3 even = [] 4 array = [] 5 for i in A: 6 if i % 2 == 0: 7 even.append(i) 8 else: 9 odd.append(i) 10 11 for i in range(len(even)): 12 array.append(even[i]) 13 array.append(odd[i]) 14 15 return array 16 17 18 print("==============测试sortArray(A)=========") 19 A = [2, 31, 4, 6, 9, 5] 20 array = sortArray(A) 21 print("array=", array) 22 23 24 def sortArray(A): 25 ‘‘‘ 26 27 :param A: 28 :return: 29 ‘‘‘ 30 array1 = [0] * len(A) 31 t = 0 32 q = 1 33 for i in A: 34 if i % 2 == 0: 35 array1[t] = i 36 t = t + 2 37 else: 38 array1[q] = i 39 q = q + 2 40 41 return array1 42 43 44 print("============测试sortArray1()===========") 45 array1 = sortArray(A) 46 print(‘array=‘, array1) 47 48 49 def sortArray2(A): 50 ‘‘‘ 51 使用切片 52 :param A: 53 :return: 54 ‘‘‘ 55 size = len(A) 56 array2 = [0] * size 57 array2[0::2] = [i for i in A if i % 2 == 0] 58 array2[1::2] = [i for i in A if i % 2 != 0] 59 60 return array2 61 62 63 print(‘----------测试sortArray2()------------‘) 64 array2 = sortArray2(A) 65 print("array2=", array2) 66 67 68 def sortArray3(A): 69 ‘‘‘ 70 71 :param A: 72 :return: 73 ‘‘‘ 74 size = len(A) 75 j = 1 76 for i in range(0, size, 2): 77 if A[i] % 2: # 奇数 78 while A[j] % 2: 79 j += 2 80 81 A[i], A[j] = A[j], A[i] 82 83 return A 84 85 86 print(‘----------测试sortArray3()------------‘) 87 array3 = sortArray3(A) 88 print("array3=", array3)
输出:
==============测试sortArray(A)========= array= [2, 31, 4, 9, 6, 5] ============测试sortArray1()=========== array= [2, 31, 4, 9, 6, 5] ----------测试sortArray2()------------ array2= [2, 31, 4, 9, 6, 5] ----------测试sortArray3()------------ array3= [2, 31, 4, 9, 6, 5]
标签:测试 app sort style while -- 排序 描述 数组
原文地址:https://www.cnblogs.com/rounie/p/13025986.html