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