A
A
Alexey Belov2018-11-01 17:07:53
Python
Alexey Belov, 2018-11-01 17:07:53

How does this function work for finding palindromes?

Hello everyone, I need to understand how this function works, namely such moments, with cps we get a matrix, but why expand it by 2, how will it be used further, MB someone knows this algorithm, send the link.

def pal(str): 
    N = len(str) 
    cps = [[0 for i in range(N + 2)]for j in range(N + 2)] 
    
    for i in range(N): 
        cps[i][i] = 1

    for L in range(2, N + 1):
        for i in range(N): 
            k = L + i - 1
            if (k < N): 
                if (str[i] == str[k]): 
                    cps[i][k] = (cps[i][k - 1] +
                    cps[i + 1][k] + 1) 
                else: 
                    cps[i][k] = (cps[i][k - 1] +
                    cps[i + 1][k] -
                    cps[i + 1][k - 1]) 

    return cps[0][N - 1]

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
B
bogolt, 2018-11-01
@bogolt

I recommend that you display the matrices after each pass of the loop, I think that this will lead to an understanding of its work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question