如何将for循环转换为递归方法? [英] How do I convert a for loop to a recursive method?

查看:58
本文介绍了如何将for循环转换为递归方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我实现了for循环作为递归方法.

Currently, I implement a for loop as a recursive method.

for i in range(len(list)):
   **implementation code goes here**

如何将其实现为递归方法?

how do I implement this as a recursive method?

我打算遍历一个列表,检查每个项目是否在另一个可接受的可能值列表中.如果是这样,我会对此采取某些措施.否则,我会执行其他操作.

I am planning on going through a list, checking if each item is in another list of accepted possible values. If so, I do certain actions on it. Else, I do other actions.

推荐答案

标准的结构递归公式(如果使用的是Scheme等功能语言,则使用该公式)将递归地解构列表:

The standard structural recursive formula (and the one you'd use if you were using a functional language like Scheme) would be to deconstruct the list recursively:

func([]) => nothing
func([x, ...]) => do_stuff(x), func([...])

因此,执行此操作的功能性"方法是获取一个列表(而不是索引),然后递归到较小的列表上:

Therefore, the "functional" way to do this would be to take a single list (not an index), and to recurse on smaller lists:

def rec_list(l):
    if not l: return # empty list case
    # process l[0]
    return rec_list(l[1:])

请注意,由于 l [1:] ,这是非常低效的,但它是理解更复杂的递归构造(例如,在二叉树上递归)的基础.

Note that this is terribly, terribly inefficient because of the l[1:], but it's the basis for understanding more complex recursive constructs (e.g. recursing on binary trees).

通过这种结构递归,我们可以做一些有趣的事情.例如,以下是您使用功能语言反向列表的方法:

We can do interesting things with this kind of structural recursion. For example, here's how you'd reverse a list in a functional language:

def rev_list(l):
    if not l: return []
    return rev_list(l[1:]) + [l[0]]

(当然,您可以在Python中执行 l [::-1] ,但在这里我们试图展示如何递归完成).

(Of course, you could just do l[::-1] in Python, but here we're trying to show how it would be done recursively).

这篇关于如何将for循环转换为递归方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆