Paw in Data
Paw in Data

Reputation: 1594

How to Define a Recursive Function with 2 Arguments in Python

I mean to define the following recursive function

recursive formula

But I don't know what goes wrong in my code. May anyone more experienced with Python take a look into that? Thank you!


    import scipy.special

def F(n,k):
    if (k == 1):
        F = 1
    else:
        F = 0
        j = 1
        while (j <= n-k+1):
            a = scipy.special.binom(n,j)
            b =  F(n-j,k-1)
            F = F + a*b
            j = j + 1
    return F 

Upvotes: 0

Views: 537

Answers (2)

Nikaido
Nikaido

Reputation: 4629

You need something like this:

import scipy.special

def F(n,k):
    if (k == 1):
        return 1
    else:
        return sum(scipy.special.binom(n,j) * F(n-j,k-1) for j in range(1, n-k+2))

In your code you are reassigning to F, which you define as function (def F(n,k)), the value of an int (F = 1). In this way, when the value k is greater than 1 you get this error:

b =  F(n-j,k-1)
TypeError: 'int' object is not callable

Because now F is an int, not a function anymore

Upvotes: 1

CypherX
CypherX

Reputation: 7353

The problem with @ArielLeung's code is that it defines both the function F(n,k) and the variable returned F as F. This creates ambiguity in the variable namespace.

The following should work fine.

import scipy.special

def F(n,k):
    f = 0
    if (k == 1):
        f = 1
    else:
        f = 0
        j = 1
        while (j <= n-k+1):
            a = scipy.special.binom(n,j)
            b =  F(n-j,k-1)
            f = f + a*b
            j = j + 1
    return f

However, I would prefer @Nikaidoh's list comprehension as a much concise solution.

Upvotes: 1

Related Questions