索引器错误:检查回文时字符串索引超出范围

2024-06-26 14:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

检查回文

我对Python还不熟悉。但我做了调试。但找不到错误。你知道吗

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

调用函数:

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

输出:

{'{', '<', '_', '$', '"', ',', '&', '\\', ']', '`', '%', "'", '#', '*', '+', '>', '/', '?', '=', '^', ')', '[', '(',
'~', '!', '@', '|', '}', ':', '.', ';', '-'}
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

Tags: noinstringindexifisprintchar
2条回答

在清理字符串(删除标点和空格)之前,您将获得最低和最高索引。因此,您正在尝试访问字符串中的一个字符,该字符现在可能超出了边界。 我建议在将字符串放入回文函数之前清理它,然后获得函数本身的最低和最高索引(aka)。删除所有标点和空格后)。你知道吗

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))

只是伪代码,但我相信你明白了!你知道吗

希望有帮助!:)

你犯的错误在Andrew Grass's answer中有很好的描述。你知道吗

这里有一个建议,你可以让这一切变得更简单:

对于清理,可以使用^{}str.translate;然后将字符串的前半部分与后半部分进行比较(相反):

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]

你可以把它当作:

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

相关问题 更多 >