The following code should return the longest odd-length palindrome in a string centered at the index. So in a string 'asradarer' it should return 'radar'. Can you explain to me what the problem here is?

def get_odd_palindrome_at(word, index):
    num = 1
    new_word = ""
    while index < len(word):
        if word[index - num] == word[index + num]:
            print new_word + word[index - num:index + (num + 1)]
        num += 1
   else:
          print ""

Well, what's happening, what's going wrong with the program? Could you post the error message.

Your description is incorrect. This function will never return 'radar' on any string input, because it needs another parameter.

Your loop does not exit. You increment num, but the loop's exit expression does not depend on it.
It possibly exits on index error if num becomes too large. At first sight.

The code has indent error. The else row is loose.

The else clause is redundant without a break statement in the loop. Unless you use exceptions for something weird.

I suggest you read the problem you are solving once more. And do not forget to read your own posts before hitting the submit button.

Your problem stems from the fact that you never give index an updated value in the while loop. I would use the while loop this way ...

def get_odd_palindrome_at(word, index):
    num = 1
    new_word = ""
    while True:
        if index + num > len(word) - 1:
            break
        if word[index - num] == word[index + num]:
            print new_word + word[index - num:index + (num + 1)]
        num += 1
    else:
        print ""

word = 'asradarer'
print len(word)  # test
index = len(word)//2 
get_odd_palindrome_at(word, index)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.