【问题标题】:How to run down a list with recursion?如何使用递归来运行列表?
【发布时间】:2015-11-14 22:03:45
【问题描述】:

起初,我不得不在没有递归的情况下做到这一点(只需通过循环,这很容易)。

现在我必须用递归来做,但我不能使用任何循环。

我想我必须用递归来遍历列表,但我不太明白我的基础应该是什么,或者减少......

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

有什么想法吗?我可以举个例子来说明如何使用递归对列表索引执行操作吗?

我使用了辅助函数来做到这一点,就像@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

工作就像一个魅力。希望不会有问题。

【问题讨论】:

  • 取列表的第一个元素,然后将列表的其余部分扔给函数本身,直到列表为空。
  • 我的基础应该是什么 => len(strings) == 0
  • @omeinusch 尝试了您的建议。编辑了问题
  • 使用所谓的 累加器 可以让事情变得更简单。让long_strings(strings, N) 做一件事:调用helper(strings, N, []) 并返回该函数的结果,然后像这样定义helper():def helper(strings, N, results)。在 helper() 中,您可以将字符串附加到结果中,然后递归调用 helper(strings, N, results)。但是递归是很难的,做不到也别担心。
  • 我能举个例子说明如何使用递归对列表索引执行操作吗? 只需使用pop() 从字符串中删除字符串,然后如果字符串符合附加条件() 字符串到结果(上一条注释中显示的列表),然后递归调用helper(strings, N, results)

标签: python list python-2.7 recursion append


【解决方案1】:

这是一个如何使用accumulator的示例:

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() 调用新函数。

看看你是否可以将这些原则应用于你的问题。

正如 bjorn 在 cmets 中指出的那样,您也可以这样做:

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

【讨论】:

  • def helper(nums, total=0) ?
  • @thebjorn,那么应该是:def sum(nums, total=0) :)
  • 不..我不会覆盖sum ;-)
  • 好吧,那么my_sum(nums, total=0)
  • @Beginner,当len(strings)==0 你不想返回 0 时——毕竟你调用该函数的原因是为了得到一个长字符串列表。相反,您希望返回长字符串列表。如果你用一个列表初始化results 累加器(你会怎么做?),那么你的函数可以 append() 限定字符串到results,然后results 将包含长字符串。
猜你喜欢
  • 2023-03-17
  • 2010-09-17
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多