简体   繁体   English

在Python中开发递归函数

[英]Developing a recursive function in Python

I know I can do this with itertools, but I'm actually trying to learn how to start working with recursions. 我知道我可以使用itertools做到这一点,但实际上我正在尝试学习如何开始使用递归。

I want to take the two values in this list... 我想采用此列表中的两个值...

[0, 1]

...and create a list of lists that contain it's permutations: ...并创建包含其排列的列表的列表:

[ [0, 0], [0, 1], [1, 0], [1, 1] ]

I can do it with a comprehension and loops: 我可以通过理解和循环来做到这一点:

[ [i, j] for i in range(0, 2) for j in range(0, 2) ]

But that doesn't really scale well. 但这并不能很好地扩展。

So if someone could help me understand how to do this with a recursive function that would scale to an arbitrary number of values in the original list I would appreciate it. 因此,如果有人可以帮助我理解如何使用递归函数将其缩放到原始列表中任意数量的值,我将不胜感激。

def cartesian_product(base, n=0):
        if (n ==  len(base)-1):
                return [[i] for i in base]
        res = []
        for i in base:
                for element in cartesian_product(base, n+1):
                        res.append([i]+element)
        return res

* Input: * cartesian_product([1,2]) * 输入:* cartesian_product([1,2])

* Output: * [[1, 1], [1, 2], [2, 1], [2, 2]] * 输出:* [[1,1],[1,2],[2,1],[2,2]]

Not the best way to do, but it's recursive. 这不是最好的方法,但是它是递归的。 Each element is composed of one of the base element (1 or 2 in the exemple) + one element of the previous size (so [1] or [2]). 每个元素由基本元素之一(例如1或2)+一个先前大小的元素(即[1]或[2])组成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM