1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does my code return False using Brutal Force finding the Longest Palindrome...

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    My code has a problem: when iterating through list S, it returns False, without giving me any indication that there's an error. I've searched Google for possible solutions, but all the answers are similar.

    def longest_palindrome(s):
    return s == s[::-1]


    def find_palindromes_bruteforce(input_word):
    palindromes = []
    n = len(input_word)
    for i in range(n):
    for j in range(i + 1, n):
    if longest_palindrome(input_word[i:j + 1]):
    palindromes.append(input_word[i:j + 1])
    return palindromes


    s = "babad"
    print(longest_palindrome(s))


    This is what the terminal return once it start running:

    /usr/local/bin/python3.12 /Users/jaredmccarthy/Desktop/2025/ejercicios_leetcode.py
    False

    Process finished with exit code 0


    longest_palindrome(word) is supposed to check if a word is a palindrome by comparing it with its reverse. then find_palindromes_bruteforce(input_word) takes that input word and iterates over the possible ones checking if it is a palindrome and returns the list of found words.

    I'm waiting for the code to return me with that word s = "badad" that will return s = "bab". is there someone who can explain me in an easy way to how it works and make it work to understand it better? I will appreciate it.

    Continue reading...

Compartilhe esta Página