2014-10-28 78 views
-1

我主要是Java用戶,但是對於我的GCSE,我必須使用Python。 我正忙着找一個算法找回文數字。代碼是一團糟,因爲我還沒有完全弄清楚Python的語法。和.Two-沒有縮短算法,除了使它從較高的數字開始並向後工作。 的代碼如下的Python 3.4.1:如何修復IndexError:字符串索引超出範圍

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()的無處不在。

回答

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 
相關問題