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)



虽然做了出来,但我觉得方法还不完善,希望大家可以提提意见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值