- 论坛徽章:
- 0
|
回复 6# ssfjhh
写了个递归的代码,按照你的思路,还能改进吗?
、- def printResult(A,a,b):
- result = []
- for ll,ai in zip(A,a):
- result.append( ' {} * {} '.format(ll,ai))
- print "+".join(result)+" = {} ".format(b)
- def solveEq(a,b,P,A,i):
- if i == len(P):
- s = sum([ai*Ai for Ai,ai in zip(A,a)])
- if s == b :
- printResult(A,a,b)
- return
- for j in range(P[i]):
- A[i] = j
- solveEq(a,b,P,A,i+1)
- a = (1,2,3)
- b = 10
- P = [b/ai+1 for ai in a ]
- A = [0] * len(a)
- solveEq(a,b,P,A,0)
复制代码 结果:- 0 * 1 + 2 * 2 + 2 * 3 = 10
- 0 * 1 + 5 * 2 + 0 * 3 = 10
- 1 * 1 + 0 * 2 + 3 * 3 = 10
- 1 * 1 + 3 * 2 + 1 * 3 = 10
- 2 * 1 + 1 * 2 + 2 * 3 = 10
- 2 * 1 + 4 * 2 + 0 * 3 = 10
- 3 * 1 + 2 * 2 + 1 * 3 = 10
- 4 * 1 + 0 * 2 + 2 * 3 = 10
- 4 * 1 + 3 * 2 + 0 * 3 = 10
- 5 * 1 + 1 * 2 + 1 * 3 = 10
- 6 * 1 + 2 * 2 + 0 * 3 = 10
- 7 * 1 + 0 * 2 + 1 * 3 = 10
- 8 * 1 + 1 * 2 + 0 * 3 = 10
- 10 * 1 + 0 * 2 + 0 * 3 = 10
复制代码 |
|