递归地将列表拆分为两部分

时间:2016-03-11 05:29:27

标签: python recursion

问题是如何将其变成递归函数。

  

将列表拆分为两部分。 even包含偶数索引元素,odd包含奇数索引元素。偶数和奇数的顺序并不重要。

 def split_alt(self):
    """
    -------------------------------------------------------
    Split a list into two parts. even contains the even indexed
    elements, odd contains the odd indexed elements.
    Order of even and odd is not significant.
    -------------------------------------------------------
    Postconditions:
        returns
        even - the even indexed elements of the list (List)
        odd - the odd indexed elements of the list (List)
        The list is empty.
    -------------------------------------------------------
    """
    even = List()
    odd = List()

    while self._front is not None:
        new_node = self._front
        self._front = self._front._next
        new_node._next = even._front
        even._front = new_node

        if self._front is not None:
            new_node = self._front
            self._front = self._front._next
            new_node._next = odd._front
            odd._front = new_node

    odd._count = self._count // 2
    even._count = self._count - odd._count
    self._count = 0
    return even, odd

    def split_alt(x):
     if not x:
       return []
     if x[0] % 2 == 0: #even
       return [x[0]] + split_alt(x[1:])
     else:
       return split_alt(x[1:]) + [x[0]]

这是我到目前为止所做的,我不确定它是否正确。有人可以帮帮我吗?提前谢谢。

因此,如果列表包含值'a', 'b', 'c', 'd', 'e',则even应包含'a', 'c', 'e',而odd应包含'b', 'd'

2 个答案:

答案 0 :(得分:1)

虽然rofls的方式更像Pythonic,但它不是递归的。

def split_list(l):
    def sub(index, l, odd, even):
        try:
            if index % 2 == 0:
                even.append(l[index])
            else:
                odd.append(l[index])
        except IndexError: # we've reached the end of the list
            return odd, even
        return sub(index+1, l, odd, even) # recursive call by advancing the index
    return sub(0, l, [], []) # initial call to function

答案 1 :(得分:0)

代码只有一个函数定义,如下所示。主要思想是:从列表尾部“剪切”两个元素,然后我们得到子列表。接下来,使用子列表递归调用list_split(),直到子列表的长度达到1(原始列表的长度为奇数)或0(当原始列表的长度为偶数时)。

def list_split (list, even, odd):
    if (len(list) % 2 == 0 and len(list) != 0):
        list_split (list[0:len(list) - 2], even, odd) #recursive call sublist
        odd.append(list[len(list) - 1])
        even.append(list[len(list) - 2])
    elif (len(list) % 2 == 1 and len(list) != 1):
        list_split (list[0:len(list) - 2], even, odd) #recursive call sublist
        even.append(list[len(list) - 1])
        odd.append(list[len(list) - 2])
    elif (len(list) == 1):
        even.append(list[0])
        return
    elif (len(list) == 0):
        return


# testing       
even = []
odd = []
list_split(['a', 'b', 'c', 'd', 'e'], even, odd)
print (odd)
print (even)