排序奇数和偶数的列表

时间:2014-06-28 07:59:47

标签: python list recursion

给出一个数字列表,我希望对列表进行排序,使奇数出现在偶数之前,我希望以递归方式进行,因为使用循环并不困难。我得到错误最大递归深度超过.here& #39;我的代码:

def sep(l,i,j):
    def swap(l,i,j):
        (l[i],l[j]) = (l[j],l[i])
    n = len(l)
    i = 0
    j = n-1

    if l[i]%2 == 0:
        swap(l,i,j)
        j-=1
        return l 

   else:
        return  sep(l,i+1,j)
l =[5,13,12,4,6,9]
i =0
j =len(l)-1
print(sep(l,i,j))

4 个答案:

答案 0 :(得分:1)

def rec(lst, start, end):
    if start == end:
        return lst
    elif lst[start] % 2 == 0 and lst[end] % 2 == 1:
        lst[start], lst[end] = lst[end], lst[start]
        return rec(lst, start+1, end-1)
    elif lst[start] % 2 == 0:
        return rec(lst, start, end-1)
    else:
        return rec(lst, start+1, end)



def rec_sort(lst):
    return rec(lst, 0, len(lst)-1)


print rec_sort([1,2,3,4,5,6])

<强>输出:

[1, 5, 3, 4, 2, 6]

答案 1 :(得分:0)

此代码以预期的方式工作。至于为什么你的代码不起作用,我认为@ AMacK&@ JohnBarca的评论应该会有所帮助:

lst = [5,13,12,4,6,9]

def sep(l,i):
    if len(l)-i < 2: return
    for j in range(len(l)-i):
        if l[i]%2==0 and l[i+j]%2==1:
            l[i],l[i+j] = l[i+j],l[i]
    sep(l,i+1)

sep(lst,0)

>>> print lst
[5, 13, 9, 4, 6, 12]

答案 2 :(得分:0)

# called with list, 0, len(list)-1
def sep(lst, first, last):
    def swap(l, x, y):
        l[x], l[y] = l[y], l[x]
    # basecase: done searching list
    if first == last or first > last:
        return lst
    # even left: continue ignoring the first
    if lst[first] % 2 == 0:
        return sep(lst, first+1, last)
    # odd left: continue ignoring the last
    if lst[last] % 2 == 1:
        return sep(lst, first, last-1)
    swap(lst, first, last)
    return sep(lst, first+1, last-1)
l = [5,13,12,4,6,9]
print sep(l, 0, len(l)-1)

是的,你的问题在于评论。如果你继续在函数中设置i和j,任何需要递归调用sep的列表都会继续重复,将i设置为0,将j设置为整个列表的长度减去1

要调用递归,您不需要设置i和j,每次都需要递增和递减它们。他们就是你知道你的递归完成的方式。一旦您通过列表移动到列表中的每个指针彼此指向或已经相互通过的点,那么您就完成了。

完成后你不想返回1,你想要返回列表。您还希望确保在交换后减少j。

答案 3 :(得分:0)

如果不是使用自己的函数或递归的情况,sorted()适合这个

arr = [5,13,12,4,6,9]
arr = sorted(arr, key=lambda x: (x % 2 == 0, x))
print(output)

<强>输出

[5, 9, 13, 4, 6, 12]