如果我有一个函数A,它可以在给定矩阵上应用某个规则来生成另一个矩阵,我将其称为原始矩阵的下一个状态,该函数也可以通过函数确定矩阵的最终状态给定时间N(在原点上应用规则,再次将规则应用于原始矩阵的下一个状态,并应用规则应用规则... N次)。
假设对于给定的矩阵,对其应用规则5次,最终矩阵与原始矩阵相同,我们称该矩阵的周期为5。 < /强>
我还有另一个函数B,我怎样才能使functionB能够在functionA的同一规则下确定给定函数的周期,并返回句点?我只是不知道如何开始它...谢谢你。
def functionA(origin_matrix,N_times):
#apply rule on the origin_matrix to generate another matrix which is the next sate of it.
#apply rule on origin_matrix for N_times
return the_final_matrix
def functionB(origin_matrix):
#determine the period of the the origin_matrix.
return period
答案 0 :(得分:6)
使用带有临时结果和计数器的for循环或while循环。后一种方法效率最高(一般而言)。
简单版本,伪代码:
iterations = 0;
tmp = origin_matrix;
do
tmp = operation(tmp);
iterations += 1;
while tmp != origin_matrix;
return iterations;
编辑:你也可以使用简单的while结构:
while True:
tmp = operation(tmp)
iterations += 1
if tmp == origin_matrix:
break # Or you could return here.
编辑:那是针对functionB的。我不知道他们是单独的问题。对于该示例,operation(x)= functionA(x,1)。
对于functionA,你最有可能使用for循环。伪代码:
matrix = origin_matrix
for i in range(N_times):
matrix = operation(matrix)
return matrix