具有改变的可变参数数量的递归函数Python

时间:2018-01-20 20:52:17

标签: python-3.x recursion

python newbie here。

我正朝着递归,记忆(两个变量的公式)函数的方向努力,但我目前还有一段距离。

所以目前我认为我的主要问题是,在我最初调用函数fun1并进行一些操作之后,我想再次将更改的初始agruments组传递给函数。但是当我这样做时,错误说它只收到一个参数 - 一个元组。这是错误和底部的脚本。目前我只想尝试一次删除一个参数(p1tpn),直到只剩下一个,但实际情况会有所不同。

fun1(2,4,6)

I was called with 3 arguments: (2, 4, 6)
with arg <class 'tuple'>
[arg] is type: <class 'list'>
list on arg [2, 4, 6] and is type: <class 'list'>
argList is: [2, 4, 6]

[[2, 4], [6]]

first arg is: 2
rest of arg is: [4, 6]
I was called with 1 arguments: ([4, 6],)
with arg <class 'tuple'>
[arg] is type: <class 'list'>
list on arg [[4, 6]] and is type: <class 'list'>
argList is: [[4, 6]]

[[[4, 6]]]

first arg is: [4, 6]
rest of arg is: []

所以我看到第一次通话完成后,rest of arg is [4, 6],进入第二次&#34;呼叫/实例化&#34;它说这是一个论点。我猜其他的东西本来可以拿出来(memoize),但是人们可以看到它们还没有被实现。

def partition(collection):
    if len(collection) == 1:
        yield [ collection ]
        return

    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[ first ] + subset]  + smaller[n+1:]
        # put `first` in its own subset 
        yield [ [ first ] ] + smaller

def memoize(f):
    memo = {}
    def helper(x):
        if x not in memo:
            memo[x] = f(x)
        return memo[x]
    return helper

fun1 = memoize(fun1)

def fun1(*arg):
    lArg = len(arg)
    firstNumber = arg[0]
    print("I was called with", len(arg), "arguments:", arg)
    print("with arg", type(arg))
    argList = list(arg)
    print("argList is:",argList)
    print("first arg is:", arg[0])
    p1tpn = argList[1:]
    print("rest of arg is:", p1tpn)
#
    if firstNumber == 1 : return 1
    else: fun1(p1tpn)

我从Set partitions in Python

获得的分区函数定义

1 个答案:

答案 0 :(得分:1)

def fun1(*args)(请注意,这是函数定义)语法将任意数量的传入参数打包到列表中。在你的递归调用中,你确实传递了一个参数,即列表本身。您将要修改对 un 的递归调用打包函数调用的参数列表fun1(*p1tpn)

以下是有关***运算符What does ** (double star/asterisk) and * (star/asterisk) do for parameters?的语义的更多信息

另外,作为旁注,您可以使用内置lru_cache进行记忆:

https://docs.python.org/3/library/functools.html#functools.lru_cache