[Python] Python is retrieving data from nowhere (?)

Discussão em 'Python' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    Currently I've been doing some tests to prepare for an interview to find the longest palindrome, and for some reason Python is retrieving data that is not supposed to.

    A brief resume about the issue... If you read the code and the output bellow, the only part of the code that I insert anything into longest_palindrome is inside a single IF statement. I also put a print() function to catch whatever data is catching from the IF statement, and for some reason even if it does not print ['b', 'a', 'b', 'a'], I get ['b', 'a', 'b', 'a'] as result ???

    Python version I am using:


    3.11.10 | packaged by conda-forge | (main, Oct 16 2024, 01:19:04) [GCC 13.3.0]
    ​

    Here is the code

    CODE

    def longestPalindrome(s: str) -> str:
    aux = 0
    while True:
    if s[-(aux+1)] not in s[:-(aux+1)]:
    aux+=1
    else:
    break
    s = s if aux == 0 else s[:len(s)-aux]

    longest_palindrome= []
    for idx, value in enumerate(s):
    current = [value]
    if value not in s[idx+1:]:
    continue
    for v in (s[idx+1:]):
    current.append(v)
    if current == list(reversed(current)):
    print('if logic current=', current)
    longest_palindrome = current if len(longest_palindrome) < len(current) else longest_palindrome
    return longest_palindrome

    res = longestPalindrome("babad")
    print('resut:', res)


    OUTPUT

    if logic current= ['b', 'a', 'b']
    if logic current= ['a', 'b', 'a']
    result: ['b', 'a', 'b', 'a']

    Continue reading...

Compartilhe esta Página