Examples of recursion and generators

Print out the Yanghui triangle, like this:

# Expect output:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Recursive way:

def triList(n):
	L=[1]
	if n>1:
		cL=triList(n-1)			
		for i,d in enumerate(cL):
			if i!=len(cL)-1:
				L.append(d+cL[i+1])
		L.append(1)
	return L

def triangles(n):
	i=1
	while i<=n:
		yield triList (s)
		i+=1
	return 'done'

Generator way:

def triangles(n):
	L=[1]
	i=1
	while i<=n:
		if i>1:
			t=[L[x]+L[x+1] for x in range(i) if x+1<len(L)]
			L=[1]
			for d in t:
				L.append(d)				
			L.append(1)
		yield L
		i+=1	 
	return 'done'

implement:

x = triangles(10)
for g in x:
	print(g)



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325926650&siteId=291194637