Python 函数中带有可选输入的196算法
我想做的是:Python 函数中带有可选输入的196算法,python,function,Python,Function,我想做的是: 如果用户在调用函数时指定return\u length=True,则应返回1加上算法达到回文数所需的步数。例如,如果输入为5280且return_length=True,则函数应返回4(请注意,这是序列[528061051112123232]中的条目总数)。例如,当输入为11时,函数应该返回1,因为它已经是一个回文数 如果用户未指定return\u length或指定return\u length=False,则函数应返回算法终止时的回文数。例如,输入5280时,算法应返回2323
return\u length=True
,则应返回1加上算法达到回文数所需的步数。例如,如果输入为5280且return_length=True
,则函数应返回4(请注意,这是序列[528061051112123232]中的条目总数)。例如,当输入为11时,函数应该返回1,因为它已经是一个回文数return\u length
或指定return\u length=False
,则函数应返回算法终止时的回文数。例如,输入5280时,算法应返回23232(整数,而不是字符串)。类似地,对于89的输入,它应该返回整数8813200023188def 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__'
但是仍然是不获取回文数或回文数序列。
x[::-1]
对数字不起作用:
>>> 42[::-1]
TypeError: 'int' object has no attribute '__getitem__'
您需要将其转换为字符串,将其反转,然后将其转换回int
:
>>> int(str(42)[::-1])
24
第二,线路
x==x+x[::-1]
什么都不做。不要混淆
=
和=
你不能得到整数的“切片”。首先需要将其转换为字符串x[:-1]
类似这样的内容:
def algo(r,ret_len=None):
count=0
while 1:
r=str(r)
if r==r[::-1]:
break
else:
count+=1
r=int(r)+int(r[::-1])
return count+1 if ret_len else r
print (algo(5280,True))
print (algo(5280))
print (algo(89,True))
print (algo(89))
输出:
4
23232
25
8813200023188
基本上,它会生成一个回文数,然后返回回文或序列以获取回文数。您的信息很有用,并且已经消除了我的错误,但现在我仍然无法获取回文数。我的新代码是:defalg196(x,y=false):如果y==false:whilestr(x)==str(x)[::-1]:x=str(x)+str(x)[::-1]返回x,否则:seq=[x]而str(x)==str str(x)[::-1]:x=str x)+str x[:::-1]seq.append(x)返回seq@user1698174:
str(x)+str(x)[::-1]
不是您想要的。当x
为42时,则给出“42”+“24”==“4224”
。您需要x+int(str(x)[::-1])
它给出42+24=66
我认为在alg196函数中应该是count=0
。
def alg196(n, return_length=False):
count = 1
while not is_palindrome(n):
n = n + reverse(n)
count += 1
return count if return_length else n
def algo(r,ret_len=None):
count=0
while 1:
r=str(r)
if r==r[::-1]:
break
else:
count+=1
r=int(r)+int(r[::-1])
return count+1 if ret_len else r
print (algo(5280,True))
print (algo(5280))
print (algo(89,True))
print (algo(89))
4
23232
25
8813200023188