Start New Discussion within our Software Development Community

Hi,if i have a function A,which can apply a certain rule on a given matrix to generate a another matrix which i call it the next state of the origin matrix,also the function can determine the the final state of the matrix by given times N(apply the rule on origin,and apply the rule on the next state of the origin matrix again,and apply rule apply rule... for N times).

So suppose for a given matrix,apply the rule on it for 5 times and the final matrix become the same as the origin matrix,and we call that matrix's period is 5.

And I have another function B,how can i make the functionB can determine the period of a given function under the same rule of the functionA,and return the period?I just have no idea how to start to make it...Thanks in advance.

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

There are many ways to do this. Here is a function which computes the index for which the first item of a sequence is repeated

def first_return(sequence):
    it = iter(sequence)
    first_item = it.next()
    for i, item in enumerate(it):
        if item == first_item:
            return i+1
    return -1 # if the first item was not repeated in the sequence

if __name__ == "__main__":
    print first_return("abcdefghasdjklfhhsdf")

Now, you can build a sequence with your functionA like this

def all_states(amatrix):
    while True:
        yield amatrix
        amatrix = functionA(amatrix, 1)

def functionB(amatrix):
    return first_return(all_states(amatrix))
This article has been dead for over six months. Start a new discussion instead.