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']
>Solution :
In your code, it’s possible that the two variables current and longest_palindrome refer to the same list object, because there is an assignment of current to longest_palindrome.
The value of longest_palindrome is printed inside an if statement, but current is modified outside the if statement (by calling current.append).
Therefore it’s possible that the value that is returned is different from the last value that is printed, if the condition of the if statement was false in the last iteration.