python:YY校招試題--傳入一個數組進行排序,奇數在前進行升序,偶數在後進行降序
阿新 • • 發佈:2018-12-09
a = input() # 輸入使用空格進行進行間隔 num = [int(n) for n in a.split()] print(num) def mysort(a,ascending=True): # 插入排序,a為list陣列,ascending=True時升序,ascending = False降序 len_a = len(a) for i in range(1,len(a)): x = a[i] j = i if ascending ==True: while j>0 and a[j-1]>x: # 升序 a[j] = a[j-1] j -=1 a[j] = x if ascending == False: while j>0 and a[j-1]<x: # 降序 a[j] = a[j-1] j -=1 a[j] = x return a ji =[n for n in num if n%2==1 ] # 遍歷num奇數放入ji中 ou =[n for n in num if n%2==0 ] # 遍歷num偶數放入ou中 ji = mysort(ji,True) # 升序排序 ou = mysort(ou,False) # 降序排序 print(ji+ou) # 陣列組合 ''' 輸入: 1 2 3 4 5 7 輸出: [1, 2, 3, 4, 5, 7] [1, 3, 5, 7, 4, 2] '''