递归 - 从列表中删除重复项

时间:2016-03-11 07:42:30

标签: python recursion

问题是编写一个递归函数,从列表中删除重复项。

提示:它可以用两个辅助功能实现。

该列表包含以前存在的每个值中的一个且仅一个 在列表中。保留每个值的第一次出现。

实现并测试此方法的递归版本

def clean(self):

    key_node = self._front

    while key_node is not None:
        # Loop through every node - compare each node with the rest
        previous = key_node
        current = key_node._next

        while current is not None:
            # Always search to the end of the list (may have > 1 duplicate)
            if current._value == key_node._value:
                # Remove the current node by connecting the node before it
                # to the node after it.
                previous._next = current._next
                self._count -= 1
            else:
                previous = current
            # Move to the _next node.
            current = current._next
        # Check for duplicates of the _next remaining node in the list
        key_node = key_node._next
    return

这就是我到目前为止,我不明白什么是辅助功能:

def clean(list):
   i = 1
   if len(list) == 0:
     return []
   elif len(list) == 1:
      return list
   elif list[i] == list[i-1]:
       del list[i]
    return clean(list[i:])

示例:对于list = [1,2,2,3,3,3,4,5,1,1,1],答案为[1,2,3,4,5,1]

2 个答案:

答案 0 :(得分:0)

这是一个调用另一个递归函数并生成所需结果的函数。我想你可以称clean2为辅助功能,但是,和你一样,我并不确切地知道它应该是什么意思。它是一个相当荒谬的代码片段,但它没有使用任何标准库函数,它修改了x。我希望它非常低效。如果我为日常工作写这篇文章,我可能会辞职。

def clean(x):
    clean2(x, 1)

def clean2(x, i):
    if i >= len(x):
        return
    if x[i] == x[i - 1]:
        del x[i]
        clean2(x, i)
    else:
        clean2(x,i+1)


the_list = [1,2,2,3,3,3,4,5,1,1,1]
clean(the_list)
print(the_list)

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

答案 1 :(得分:0)

这是一个使用辅助函数go来实际实现递归的递归定义。我们的想法是外部clean函数可以接受任何可迭代对象(例如列表),并且它总是生成一个值列表:

def clean(iterable):
    def go(iterator, result):
        try:
            x = next(iterator)
            if result == [] or result[-1] != x:
                result.append(x)
            return go(iterator, result)
        except StopIteration:
            return result

    return go(iter(iterable), [])

clean只调用本地定义的go函数,传递迭代器和最终结果值(最初为空列表)。 go然后尝试推进迭代器并将引用的值与result的结尾进行比较:如果它不同(或者结果为空),则附加值。 go然后递归。

相关问题