Python 如何使用递归运行列表?

Python 如何使用递归运行列表?,python,list,python-2.7,recursion,append,Python,List,Python 2.7,Recursion,Append,起初,我必须在没有递归的情况下完成它(只是通过循环,这很容易) 现在我必须使用递归,但不允许使用任何循环 我想我必须用递归来运行这个列表,但是我不太明白我的基础应该是什么,或者是缩减 def long_strings_rec(strings, N): ''' strings - a list of strings N - an integer Returns all strings in 'strings' of length bigger then 'N'

起初,我必须在没有递归的情况下完成它(只是通过循环,这很容易)

现在我必须使用递归,但不允许使用任何循环

我想我必须用递归来运行这个列表,但是我不太明白我的基础应该是什么,或者是缩减

def long_strings_rec(strings, N):
    '''
    strings - a list of strings
    N - an integer
    Returns all strings in 'strings' of length bigger then 'N'
    (This function is recursive and does not use loops)
    '''

    # Your code for question #2 (second function) starts here

    # Your code for question #2 (second function) ends here
有什么想法吗?我能举个例子说明如何使用递归对列表和索引执行操作吗

我使用了helper函数来实现这一点,就像@7stud建议的那样:

def helper (strings, K, results):
    if len(strings) == 0:
        return 0
    elif len(strings[0]) > K:
        results.append(strings[0])
        strings.pop(0)
    else:
        strings.pop(0)
    helper(strings, K, results)
    return results


def long_strings_rec (strings, N):
    '''
    strings - a list of strings
    N - an integer
    Returns all strings in 'strings' of length bigger then 'N'
    (This function is recursive and does not use loops)
    '''

    # Your code for question #2 (second function) starts here
    return helper(strings, N, [])
    # Your code for question #2 (second function) ends here

工作得很有魅力。希望它没有问题。

下面是一个如何使用
累加器的示例:

def sum(nums):
    return helper(nums, 0)  #0 is the initial value for the accumulator

def helper(nums, total):    #total is the accumulator
    if len(nums) == 0:
        return total
    else:
        num = nums.pop()
        return helper(nums, total+num) 


print sum([1, 2, 3])

--output:--
6
基本上,您需要重新定义sum(),以便它接受一个额外的累加器参数变量,然后让sum()调用新函数

看看你是否能把这些原则应用到你的问题上

正如比约恩在评论中指出的,你也可以这样做:

def mysum(nums, total=0):
    if len(nums) == 0:
        return total
    else:
        num = nums.pop()
        return sum(nums, total+num) 


print mysum([1, 2, 3])

--output:--
6

获取列表的第一个元素,然后将列表的其余部分抛出到函数本身,直到列表为空。我的基应该是什么=>
len(strings)==0
@omeinusch尝试了一下您的建议。一个让事情变得更容易的提示是使用所谓的累加器。让
long_strings(strings,N)
做一件事:调用
helper(strings,N,[])
并返回该函数的结果,然后像这样定义helper():
def helper(strings,N,results)
。在helper()内部,您可以向结果()附加一个字符串,然后递归调用
helper(strings,N,results)
。但是递归很难,所以如果你做不到也不用担心。我能举个例子说明如何使用递归对列表和索引执行操作吗?只需使用
pop()
从字符串中删除字符串,然后如果字符串限定将append()字符串附加到结果(上一条注释中所示的列表),则递归调用
helper(strings,N,results)
def helper(nums,total=0)
?@thebjorn,那么它应该是:
def sum(nums,total=0)
:)Nah。。我不会覆盖
sum
;-)那么,我的总和(nums,total=0)
@初学者,当
len(strings)==0时,您不想返回0——毕竟您调用该函数的原因是为了返回长字符串列表。相反,您希望返回长字符串列表。如果使用列表初始化
results
累加器(您会怎么做?),则函数可以将()限定字符串附加到
results
,然后
results
将包含长字符串。