简体   繁体   中英

Galton Code - From Recursive to Iterative

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM