如果我有一个函数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
Run Code Online (Sandbox Code Playgroud)
使用带有临时结果和计数器的for循环或while循环.后一种方法最有效(通常).
简单版本,伪代码:
iterations = 0;
tmp = origin_matrix;
do
tmp = operation(tmp);
iterations += 1;
while tmp != origin_matrix;
return iterations;
Run Code Online (Sandbox Code Playgroud)
编辑:你也可以使用简单的while结构:
while True:
tmp = operation(tmp)
iterations += 1
if tmp == origin_matrix:
break # Or you could return here.
Run Code Online (Sandbox Code Playgroud)
编辑:那是为functionB.我不知道他们是单独的问题.对于该示例,operation(x)= functionA(x,1).
对于functionA,你最有可能使用for循环.伪代码:
matrix = origin_matrix
for i in range(N_times):
matrix = operation(matrix)
return matrix
Run Code Online (Sandbox Code Playgroud)