Search code examples
pythonpalindrome

how to debug small programs in python


I have problem with my code. I have a sentence, and this sentence has palindromic words with 5 letters each one. The sentence is: the level rotor is in the radar. As you can see, the palindromic words are: level, rotor and radar. Firstly, I grouped the words in 5 letters like this: thele helev eleve level, and so on.

My code is something like this:

test = "the level rotor is in the radar"
data = []

for i in range(len(test) - 5):
    data.append(test[i:i+6])
    print(data)

def siqpalindromics(pal):
    return pal == pal[::-1]

pal = "data"
anpal = siqpalindromics(pal)

if anpal:
    print("it is palindromic"), print(pal)
else:
    print("it isnt palindromic")

I want to print for example:

thele it isnt palindromic
helev it isnt palindromic
eleve it isnt palindromic
level it is palindromic

Thank you in advance


Solution

  • You can use a for loop to check whether each extracted word is a palindrome.

    def is_palindrome(s):
        return s == s[::-1]
    
    data = "the level rotor is in the radar"
    data = data.replace(' ', '')
    words = []
    word_length = 5
    for i in range(len(data) - word_length + 1):
        words.append(data[i:i+word_length])
    
    for word in words:
        if is_palindrome(word):
            print(f'{word} is palindromic')
        else:
            print(f'{word} is not palindromic')