YY校招试题----python:传入一个数组进行排序,奇数在前进行升序,偶数在后进行降序


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]
'''

猜你喜欢

转载自blog.csdn.net/weixin_39781462/article/details/82708795