我将问题简化为以下内容:
Xn + 1 = Xn + Yn
Yn + 1 = Yn + Zn
Zn + 1 = Zn + Xn
我知道X0,Y0,Z0的值等于1。 我想告诉python找到X1,Y1,Z1的值,然后找到X2,Y2,Z2,......等。任何人都可以帮助我吗?我想我必须使用嵌套循环,但我不确定如何去做。谢谢!
答案 0 :(得分:3)
我们在谈论的事情很简单:
x, y, z = 1, 1, 1
for i in range(10):
print("X{i} = {x}, Y{i} = {y}, Z{i} = {z}".format(**locals()))
x, y, z = x + y, y + z, z + x
由于输出无趣,所以看起来并不正确:
X0 = 1, Y0 = 1, Z0 = 1
X1 = 2, Y1 = 2, Z1 = 2
X2 = 4, Y2 = 4, Z2 = 4
X3 = 8, Y3 = 8, Z3 = 8
X4 = 16, Y4 = 16, Z4 = 16
X5 = 32, Y5 = 32, Z5 = 32
X6 = 64, Y6 = 64, Z6 = 64
X7 = 128, Y7 = 128, Z7 = 128
X8 = 256, Y8 = 256, Z8 = 256
X9 = 512, Y9 = 512, Z9 = 512
答案 1 :(得分:1)
以下是实现它的示例函数:
def solve_equation(n):
X = {0: 1}
Y = {0: 1}
Z = {0: 1}
for i in range(n):
print 'For n: ', i+1
X[i+1] = X[i] + Y[i]
Y[i+1] = Y[i] + Z[i]
Z[i+1] = Z[i] + X[i]
print 'X = ', X[i+1], ' Y = ', Y[i+1], ' Z = ', Z[i+1]
示例运行:
>>> solve_equation(3)
For n: 1
X = 2 Y = 2 Z = 2
For n: 2
X = 4 Y = 4 Z = 4
For n: 3
X = 8 Y = 8 Z = 8
答案 2 :(得分:0)
您可以使用递归函数。要获得更快更好的代码,您可以考虑使用 yield
def Cvalue(c,xyz , n):
if n == 0 :
res = c
else :
if xyz == 1: res = Cvalue(c,1, n-1) + Cvalue(c,2, n-1)
elif xyz == 2: res = Cvalue(c,2, n-1) + Cvalue(c,3, n-1)
elif xyz == 3: res = Cvalue(c,3, n-1) + Cvalue(c,1, n-1)
else: print("Error\n")
return res
def XYZvalues(x0, y0, z0, n):
x = Cvalue(x0,1, n)
y = Cvalue(y0,2, n)
z = Cvalue(z0,3, n)
return (x, y , z)
print(XYZvalues(1,1,1, 3))