如何修复IndexError:字符串索引超出范围

时间:2014-10-28 20:48:34

标签: python algorithm indexing

我主要是Java用户,但对于我的GCSE,我必须使用Python。 我正在制作一个算法来找到回文数字。 代码是一个很大的混乱,因为我.One-还没有完全弄清楚Python语法。并且。两个 - 没有缩短算法,除了从更高的数字开始并向后工作。 python 3.4.1的代码如下:

print("This program will find the nearest palindromic number to a given value.")
countN = input("Input a number above 0 to find the nearest palindromic number")
countN = str(countN)
nl = len(countN) # Number length
pf = 0 # Palindrome found
while(pf == 0 and int(countN)>=0): #While no palindrome found and count is bigger than 0
 ep = nl # end pointer
sp = -1 # start pointer
 while(int(ep) >= sp):
if(int(countN[ep]) == int(countN[sp])):
 ep = ep-1
 sp = sp+1
print(count + " is a palindrome.")
 pf = 1
else:
print(count + " is not a palindrome.")
countN = countN - 1    

我只是想改变指针位,它应该与IF语句分开吗?

无论如何,我遇到的错误如下:

>>> 
This program will find the nearest palindromic number to a given value.
Input a number above 0 to find the nearest palindroic number99
Traceback (most recent call last):
  File "C:/Python34/Computer science/palindrome finder.py", line 10, in <module>
    if(int(countN[ep]) == int(countN[sp])):
IndexError: string index out of range
>>> 

请注意:我在这里搜索了一个答案,部分原因是str()和int()无处不在。

1 个答案:

答案 0 :(得分:0)

你的问题在这里

nl = len(countN)  # this is the length of your string

然后你说

ep = nl 
...
int(countN[ep]...

如果您的长度为10的字符串,则有效索引为09,因此10超出范围。

最快的解决方法是将while循环之外的初始化更改为。

ep = nl -1
sp = 0

然而,为了解决这个问题,我只会这样做

def isPalindrome(x):
    text = str(x)     # Convert number to string
    return text == text[::-1]   # Compare string to reversed string

>>> isPalindrome(123454321)
True

>>> isPalindrome(12345)
False