Rock2019
Rock2019

Reputation: 25

IndexError: string index out of range in checking palindrome

Checking palindrome

I am new to python. But I did the debugging. But couldn't find the error.

import string

def is_palindrome(str_1, lowest_index, highest_index):
    punct = set(string.punctuation)
    print(punct)
    #remove punctuations
    no_punct = ""
    for char in str_1:
        if char not in punct:
            no_punct = no_punct + char
    print(no_punct)
    # rmv_whtspc = no_punct.rstrip()
    rmv_whtspc = no_punct.replace(' ','')
    print(rmv_whtspc)
    str_2 = rmv_whtspc.lower()
    print(str_2)
    if lowest_index > highest_index:
        return True
    else:
        if str_2[lowest_index] == str_2[highest_index]:
            return is_palindrome(str_2, lowest_index+1, highest_index-1)
        else:
            return False

Calling the function:

str_1 = "Madama I am adam"
lowest_index = 0
highest_index = len(str_1)-1
print(is_palindrome(str_1, lowest_index, highest_index))

The Output:

{'{', '<', '_', '$', '"', ',', '&', '\\', ']', '`', '%', "'", '#', '*', '+', '>', '/', '?', '=', '^', ')', '[', '(',
'~', '!', '@', '|', '}', ':', '.', ';', '-'}
Madama I am adam
MadamaIamadam
madamaiamadam

Traceback (most recent call last):
  File "recursion_5_2problem.py", line 27, in <module>
    print(is_palindrome(str_1, lowest_index, highest_index))
  File "recursion_5_2problem.py", line 19, in is_palindrome
    if str_2[lowest_index] == str_2[highest_index]:
IndexError: string index out of range

Upvotes: 1

Views: 108

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46921

the mistake you made is nicely described in Andrew Grass's answer.

here a suggestion how you could make all this a lot simpler:

for the cleanup you could use str.maketrans and str.translate; then you just compare the first half of the string to the second half (in reverse):

from string import punctuation, whitespace

repl_table = str.maketrans("", "", punctuation + whitespace)

def normalize(strg):
    # remove all punctuation and whitespace and lowercase strg
    return strg.translate(repl_table).lower()


def ispalindrome(strg):
    n2 = len(strg) // 2
    return strg[:n2] == "".join(reversed(strg))[0:n2]

you could use that then as:

strg = "Madama I am adam"
strg = normalize(strg)     # madamaiamadam
print(ispalindrome(strg))  # True

Upvotes: 0

Andrew Grass
Andrew Grass

Reputation: 252

You are getting the lowest and highest index before you clean the string (removing punctuation and whitespace). So you are trying to access a character in the string that may now be out of bounds. I'd suggest maybe cleaning the string before putting it through the palindrome function then getting the lowest and highest index in the function itself (aka. after all the punctuation and whitespace is removed).

def clean_string()
    # remove punctuation
    # remove whitespace
    return clean_string

def is_palindrome()
    # set high/low index
    # do your thing
    return result

to_check = "race car!"
cleaned = clean_string(to_check)
print(is_palindrome(cleaned))

Just pseudocode, but I'm sure you get the point!

Hope it helps! :)

Upvotes: 1

Related Questions