Python 交叉排序題

在計蒜客遇到的一道題:

輸入一行 k 個用空格分隔開的整數,依次爲 n1, n2 … nk。請將所有下標不能被 3 但可以被 2 整除的數在這些數字原有的位置上進行升序排列,此外,將餘下下標能被 3 整除的數在這些數字原有的位置上進行降序排列。

輸出包括一行,與輸入相對應的若干個整數,爲排序後的結果,整數之間用空格分隔。


我的思路如下:

1.根據原列表下標判斷,把列表的元素增添到新列表

2.新列表排序後

3.再根據原列表下標判斷,把新列表增添到最後的列表輸出


方法一:

list = [int(x) for x in raw_input().split(' ')]
list1 = []#You can't use "list1 = list2 = list3 = []" here!!!
list2 = []
list3 = []
list_sorted = []
num_list1 = num_list2 = num_list3 = 0

for x in range(len(list)):
    if (x+1) % 3 != 0 and (x+1) % 2 == 0:
        list1.append(list[x])
    elif (x+1) % 3 == 0:
        list2.append(list[x])
    else:
        list3.append(list[x])

list1 = sorted(list1)
list2 = sorted(list2, reverse = True)

for x in range(len(list)):
    if (x+1) % 3 != 0 and (x+1) % 2 == 0:
        list_sorted.append(list1[num_list1])
        num_list1 = num_list1 + 1
    elif (x+1) % 3 == 0:
        list_sorted.append(list2[num_list2])
        num_list2 = num_list2 + 1
    else:
        list_sorted.append(list3[num_list3])
        num_list3 = num_list3 + 1

print ' '.join(str(x) for x in list_sorted)



方法二:
list = [int(x) for x in raw_input().split(' ')]
list1 = []#You can't use "list1 = list2 = list3 = []" here!!!
list2 = []
list3 = []
list_sorted = []
num_list1 = num_list2 = num_list3 = 0

for x in list:
    if (list.index(x)+1) % 3 != 0 and (list.index(x)+1) % 2 == 0:
        list1.append(x)
    elif (list.index(x)+1) % 3 == 0:
        list2.append(x)
    else:
        list3.append(x)

list1 = sorted(list1)
list2 = sorted(list2, reverse = True)

for x in list:
    if (list.index(x)+1) % 3 != 0 and (list.index(x)+1) % 2 == 0:
        list_sorted.append(list1[num_list1])
        num_list1 = num_list1 + 1
    elif (list.index(x)+1) % 3 == 0:
        list_sorted.append(list2[num_list2])
        num_list2 = num_list2 + 1
    else:
        list_sorted.append(list3[num_list3])
        num_list3 = num_list3 + 1

print ' '.join(str(x) for x in list_sorted)



雖然做了出來,但我覺得方法還不完善,希望大家可以提提意見

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章