簡體   English   中英

排序一個奇數和偶數列表

[英]sort a list of odd and even numbers

給定一個數字列表,我希望對列表進行排序,以使奇數出現在偶數之前,並且我希望遞歸並就地執行它,因為使用循環並不困難。我得到了超過最大最大遞歸深度的錯誤。這是我的代碼:

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

OUTPUT:

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

此代碼以預期的方式工作。 至於為什么您的代碼不起作用,我認為@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]
# 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之后減少j。

如果不是使用自己的函數或遞歸,則sorted()適合

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

OUTPUT

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM