如何 return 一个仅包含来自数据的奇数元素的新列表,仅使用递归

How to return a new list that contains just odd elements from data using only recursion

我被要求:

编写一个函数 odds(data),它接受一个整数列表、数据作为参数,returns一个新列表只包含数据中的奇数元素,即那些不能完全整除的元素两个。您的代码不得使用 for 或 while,也不得导入任何内容。

这是我当前的代码:

def odds(data):
    """Returns a new list that contains just the odd elements from the data"""
    odd_nums = []
    if len(data) == 1:
        return []
    
    if data[0] % 2 != 0:   
        odd_nums.append(data[0])
    return odds(data[1:])

测试代码:

print(odds(\[0, 1, 12, 13, 14, 9, -11, -20\]))

---\> \[1, 13, 9, -11\]

我不确定如何递归地继续添加到 odd_nums 列表。

def odds(data):
    if not data:
        return []
    head = [ data[0] ] if data[0]%2==1 else []
    if len(data)>1:
        return head + odds (data[1:])
    else:
        return head
    
print(odds([0, 1, 12, 13, 14, 9, -11, -20]))

你几乎成功了。只需组合列表。可能为空的列表没问题。