我无法理解导致索引错误的原因,而不是寻找快速修复。但是,如果我的代码让您反感/非常无效,请告诉我。目标是生成由两个四位数的乘积产生的回文。
代码:
for x in range(10000):
for y in range(10000):
product = str(x*y)
lengthprod = len(str(product))
for digit in range(lengthprod+1):
if (product[digit]==product[lengthprod-digit]):
print x,"x",y,"=",product
回溯:
Traceback (most recent call last):
File "<pyshell#31>", line 6, in <module>
if (product[digit]==product[lengthprod-digit]):
IndexError: string index out of range
请您参考如下方法:
将数字转换为字符串通常是一个缓慢的操作,因为通常有很多可能性(整数、 float 、科学记数法,可能是分数或虚数等奇特的东西,更不用说处理前导零或超宽之类的事情了数字或四舍五入到小数点后两位)。因此,检查正整数是否为回文通常是一种更好的方法,通过重复取输入模 10 提取最后一位数字,将数字加到累加器中,在每一步乘以 10,以数字方式反转数字,然后在循环之前将输入数字除以 10。我不会说 Python,所以这是我用来反转数字的 Scheme 程序:
(define (rev n)
(let loop ((n n) (r 0))
(if (zero? n) r
(loop (quotient n 10)
(+ (* r 10) (modulo n 10))))))
然后你可以通过检查输入数字是否等于它的反转来检查数字是否是回文。
编辑:这是用 Python 编写的:
def rev(n):
r = 0
while n > 0:
r = r * 10 + n % 10
n = n // 10
return r
