[Python] Longest palindrome substring algorithm not working properly for even palindromes

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    The algorithm I wrote in Python seems to be working fine when it comes to extracting longest palindromes that have even number of characters but not for their odd counterparts:

    some_input_2 = "abdbaabeeba"
    size_of_some_input_2 = len(some_input_2)
    max = 0
    final_max = 0
    idx_center_letter = 0
    final_idx_center_letter = 0
    for j in range(2):
    for idx, letter in enumerate(some_input_2):
    i = 0
    while i <= int(size_of_some_input_2 / 2) + 1 and not idx - i < 0 and not idx + i+j >= size_of_some_input_2:
    upper_idx = idx + i +j
    bottom_idx = idx - i
    if some_input_2[bottom_idx] == some_input_2[upper_idx]:
    i = i + 1
    else:
    break
    if max < i :
    max = i #-j
    idx_center_letter = idx + 1

    if final_max <= max:
    final_max = max
    final_idx_center_letter = idx_center_letter
    print(max)
    print(idx_center_letter)
    print(some_input_2[final_idx_center_letter - final_max:final_idx_center_letter + final_max])


    here the even palindrome abdbaa is the output which is wrong. If the input was some_input_2 = "abbaabeeba" then the output would be abeeba which is correct. Any idea what is wrong here?

    Continue reading...

Compartilhe esta Página