第1,2种方法没法使用 yield.在递归中, 函数内部使用yield, 均会使该函数运行一次就退出.不再递归.
def fun(x, li=[1], n=1): if n == x+1: return li, sum(li) li.insert(0, 0) li.append(0) l = [] for i in range(n): l.append(li[i] + li[i+1]) li.pop(0) li.pop(-1) return fun(x,l, n+1) f = fun(4) print(f)
def fun(n, li =None): if not isinstance(li, list): li = [] if n == 0: return 0 l = [] for i in range (len(li)+1): if 0 < i and i < len(li): x = li[i] + li[i-1] else: x = 1 l.append(x) print(l) fun(n-1, l) f = fun(5)
def fun(): li, l = [], [] while not l: for i in range (len(li)+1): if 0 < i and i < len(li): x = li[i] + li[i-1] else: x = 1 l.append(x) li, l = l, [] yield li ff = fun() n = 0 for f in ff: print(f) n += 1 if n > 10: break