0
def galton(m, n):
    if m == 0:
        if n == 0:
            return 1
        else:
            return 0
    else:
        if n == 0:
            return 1
        else:
            return (galton(m-1, n-1) + galton(m-1, n))

Hello, does anybody know how I can change this Code from recursive to iterative? I tried it with the Galton formula, but I only got the probability.

Code:

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer / denom *(0.5**n)
karel
  • 5,489
  • 46
  • 45
  • 50

1 Answers1

0

Your galton function appears to be just a recursive implementation of 'nCr' and so any nCr function works with a slight alteration to return zero in case r > n:

def ncr(n, r):
    if r > n:
         return 0
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom
Stuart
  • 9,597
  • 1
  • 21
  • 30