title: How to prevent a recursion error implementing factorial in Python
body: <p>I'm developing a math suite and am currently having issues implementing the recursive version of the factorial function. The issue is when I use it in my Bayesian combination function:</p>
  <pre><code>C(n,k) = n! / k! * (n-k)! 
  </code></pre>
  <p>I've tested it independently and it works as it should, but as soon as I put it in my combination function, I get the error <code>Recursion Error: maximum recursion depth exceeded in comparison</code>, even for very small values of n and k.</p>
  <p>I've implemented an iterative solution which works perfectly, so why do I keep getting a recursion error?</p>
  <p>Here's the recursive implementation:</p>
  <pre><code>def factorial(n):
      if n == 1 or n == 0:
          return n
      else:
          return n * factorial(n - 1)
  </code></pre>
  <p>Here's the iterative implementation:</p>
  <pre><code>def factorial(n):
      result = 1
      for i in range(1, n+1):
          result *= i
      return result
  </code></pre>
  <p>And they are used in the combination function like so:</p>
  <pre><code>def combination(n, k):
      result = factorial(n) / (factorial(k) * factorial(n - k))
      return result
  </code></pre>
  <p>The recursive function seems to work only when k = 1.</p>
  <p>Here are some sample outputs which produces the recursion error:</p>
  <pre><code>combination(2,1) = 2
  
  combination(2,2) = 
  
  Traceback (most recent call last):
    File &quot;baysian.py&quot;, line 44, in &lt;module&gt;
      answer = combination(n, k)
    File &quot;baysian.py&quot;, line 18, in combination
      result = factorial(n) / (factorial(k) * factorial(n - k))
    File &quot;baysian.py&quot;, line 9, in factorial
      return n * factorial(n - 1)
    File &quot;baysian.py&quot;, line 9, in factorial
      return n * factorial(n - 1)
    File &quot;baysian.py&quot;, line 9, in factorial
      return n * factorial(n - 1)
    [Previous line repeated 994 more times]
    File &quot;baysian.py&quot;, line 6, in factorial
      if n == 1:
  RecursionError: maximum recursion depth exceeded in comparison
  
  </code></pre>