我正在尝试做的事情:
如果用户
return_length=True
在调用您的函数时指定,它应该返回一加算法达到回文数所需的步数。例如,输入 5280 和return_length=True
,您的函数应返回 4(请注意,这是序列 [5280, 6105, 11121, 23232] 中的条目总数)。例如,输入 11,函数应该返回 1,因为它已经是一个回文数。如果用户没有指定
return_length
或指定return_length=False
,你的函数应该返回算法终止的回文数。例如,输入为 5280,算法应返回 23232(整数,而不是字符串)。同样,输入 89 时,它应该返回整数 8813200023188。
196算法的一些背景:
取任何两位或更多的正整数,反转数字,并添加到原始数字。这是反向然后添加序列的操作。现在用这样得到的总和重复这个过程,直到得到一个回文数。这个过程可以快速为大多数整数生成回文数。例如,从数字 5280 开始产生序列 5280、6105、11121、23232。将算法应用于 1、2、3、... 的最终结果是 1、2、3、4、5、6、7 , 8, 9, 11, 11, 33, 44, 55, 66, 77, 88, 99, 121, ... (Sloane 的 A033865)。89 的值特别大,为 8813200023188。(来自http://mathworld.wolfram.com/196-Algorithm.html)
到目前为止我所拥有的:
def alg196(x, y = false):
if y==False:
while x == x[::-1]:
x==x+x[::-1]
return x
else:
seq = [x]
while x == x[::-1]:
x==x+x[::-1]
seq.append(x)
return seq
我得到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_36.py", line 10, in <module>
exec compile(u"print _support_.syseval(python, u'alg196(34)', __SAGE_TMP_DIR__)" + '\n', '', 'single')
File "", line 1, in <module>
File "/sagenb/sage_install/sage-5.3-sage.math.washington.edu-x86_64-Linux/devel/sagenb-git/sagenb/misc/support.py", line 487, in syseval
return system.eval(cmd, sage_globals, locals = sage_globals)
File "/sagenb/sage_install/sage-5.3-sage.math.washington.edu-x86_64-Linux/local/lib/python2.7/site-packages/sage/misc/python.py", line 56, in eval
eval(z, globals)
File "", line 1, in <module>
File "", line 3, in alg196
TypeError: 'int' object has no attribute '__getitem__'
我不确定如何解决此问题或确切的错误。
获取一些信息以获得答案,我有这个新代码:
def alg196(x, y = false):
if y==False:
while str(x) == str(x)[::-1]:
x=str(x)+str(x)[::-1]
return x
else:
seq = [x]
while str(x) == str(x)[::-1]:
x = str(x)+str(x)[::-1]
seq.append(x)
return seq
但是仍然没有得到回文数或回文数的序列。