Ask Your Question
1

How to return a list from a recursive function?

asked 2016-07-28 01:09:54 +0100

anonymous user

Anonymous

updated 2016-07-28 03:12:32 +0100

Hello,

I am trying to make a recursive function that will return a list but I get a SyntaxError. Here is the code working so far (just an example):

def myfactorial(n):
    if n == 1: 
        return 1
    else: 
        return n * myfactorial(n-1)

myfactorial(10)

I need to return something like this: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

I know that there is already a build in factorial function, I created this recursive function only as an example of what I am trying to get: a list. To return a list of all values of a given recursion, the steps of it...

[myfactorial(n) for n in range(1, 10)]

    [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

Now, how to put it "inside" in the recursive function?

Thank you for your attention.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2016-07-28 09:26:25 +0100

mforets gravatar image
def myfactorial(n):
    if n == 1: 
        return [1]
    else: 
        return myfactorial(n-1) + [n * myfactorial(n-1)[n-2]]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-07-28 01:09:54 +0100

Seen: 7,517 times

Last updated: Jul 28 '16