簡體   English   中英

有唯一列表時如何停止該功能?

[英]How do I stop the function when I have a unique list?

我嘗試了一個將列表中兩個相鄰重復項都刪除的函數。 刪除任何新的重復對,該功能將繼續進行,直到列表中沒有更多重復對為止。

我遇到了一個問題,即一旦我有了一個沒有相鄰重復項的列表,便該如何告訴函數停止。

def removepair(no):
  i = 1
  if len(no) == 0 or len(no) == 1:
    return no 
  while i < len(no):   
    if no[i] == no[i-1]:
      no.pop(i)
      no.pop(i-1)
      i -= 1  
    i += 1
  return removepair(no)

到目前為止,該函數在刪除后將返回0或單個元素:

輸入:[1、2、2、1]輸出:[]

要么

輸入:[4、4、4、4、4、4]輸出:[4]

但是問題是,一旦包含超過1個元素的列表,我不知道如何停止遞歸函數:

輸入:[1,2,3,3,2,1,5,6,7]
預期輸出:[5,6,7]

如果我們仔細設置遞歸,我們也許可以避免布爾標志和計數器:

def removepairs(numbers):

    if not numbers:  # base case #1, empty
        return numbers

    first, *second_on = numbers

    if not second_on:  # base case #2, one element
        return numbers

    second, *third_on = second_on

    if first == second:
        return removepairs(third_on)

    result = [first] + removepairs(second_on)

    if result == numbers:
        return numbers  # base case #3, no change!

    return removepairs(result)

print(removepairs([1, 2, 3, 3, 2, 1, 5, 6, 7]))

OUTPUT

> python3 test.py
[5, 6, 7]
> 

如果不需要遞歸函數,則可以使用以下代碼輕松完成。 我已評論印刷聲明。

def removepair(input_list):
    unique_input_list = list(set(input_list))
    output_list = list(x for x in unique_input_list if input_list.count(x)%2 == 1)
    #print('Input List: ', input_list)
    #print('Output list: ', output_list)
    return output_list

Input List:  [1, 2, 3, 3, 2, 1, 5, 6, 7]
Output list:  [5, 6, 7]

Input List:  [4, 4, 4, 4, 4]
Output list:  [4]

Input List:  [1, 2, 3, 3, 2, 1]
Output list:  []

當沒有元素從列表中彈出時,遞歸應該停止,而不是當列表幾乎為空時:

def removepair(no):
    L = len(no)
    if L <= 1:
        return no
    i = 1
    while i < len(no):
        if no[i] == no[i-1]:
            no.pop(i)
            no.pop(i-1)
            i -= 1
        i += 1
    if len(no) < L:
        # elements where popped since the list len has decreased
        return removepair(no)
    else:
        return no

您的代碼難以理解,因為它混合了遞歸和副作用。 通常,您可以使用其中一個。 在這里,您可以將一段時間的遞歸調用替換為:

def removepair(no):
    while True:
        L = len(no)
        if L <= 1:
            return no
        i = 1
        while i < len(no):
            if no[i] == no[i-1]:
                no.pop(i)
                no.pop(i-1)
                i -= 1
            i += 1
        if len(no) == L: # no elements where popped
            return no

但它不是真正的Python的,我想你不應該修改參數no在函數內部,而是返回一個新的列表。 為什么不遍歷該列表並且不復制結果中的重復項呢?

def removepair(no):
    ret = []
    for e in no:
        if ret and e == ret[-1]: # current element is the same as the last element
            ret.pop()
        else:
            ret.append(e)
    return ret

或折疊:

def removepair(no):
    import functools
    return functools.reduce(lambda acc, x: acc[:-1] if acc and acc[-1]==x else acc+[x], no, [])

暫無
暫無

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

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