版权声明:/*本文为博主原创文章,博主允许后方可转载哦。*/ https://blog.csdn.net/qq_32666555/article/details/72731548
在计蒜客遇到的一道题:
输入一行 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)
虽然做了出来,但我觉得方法还不完善,希望大家可以提提意见