ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 28 Jul 2016 09:26:25 +0200How to return a list from a recursive function?https://ask.sagemath.org/question/34251/how-to-return-a-list-from-a-recursive-function/ 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.Thu, 28 Jul 2016 01:09:54 +0200https://ask.sagemath.org/question/34251/how-to-return-a-list-from-a-recursive-function/Answer by mforets for <p>Hello,</p>
<p>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):</p>
<pre><code>def myfactorial(n):
if n == 1:
return 1
else:
return n * myfactorial(n-1)
myfactorial(10)
</code></pre>
<p><strong>I need to return something like this: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]</strong></p>
<p><strong>I know that there is already a build in factorial function</strong>, 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...</p>
<pre><code>[myfactorial(n) for n in range(1, 10)]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
</code></pre>
<p>Now, how to put it "inside" in the recursive function?</p>
<p>Thank you for your attention.</p>
https://ask.sagemath.org/question/34251/how-to-return-a-list-from-a-recursive-function/?answer=34259#post-id-34259 def myfactorial(n):
if n == 1:
return [1]
else:
return myfactorial(n-1) + [n * myfactorial(n-1)[n-2]]
Thu, 28 Jul 2016 09:26:25 +0200https://ask.sagemath.org/question/34251/how-to-return-a-list-from-a-recursive-function/?answer=34259#post-id-34259