#Start with a base case of 0 = "0" and fill in the results as they are computed
def n(x, m={0:'0'}):
if x not in m:
#Didn't have the answer, lets compute it.
m[x] = '{0}{1}{0}'.format(n(x-1), x)
#Look up what the answer is because we already computed it
return m[x]
for x in range(5):
print(n(x))
结果:
^{pr2}$
要处理大于9的整数,可以尝试如下操作:
def n(x, m={0:'0'}):
if x not in m:
lX = x
if x > 9:
lX = str(x)
#Take the integer like 123, format it and swap
#it but share the last character. i.e. 123 -> 12321
lX = '{}{}'.format(x,lX[::-1][1:])
m[x] = '{0}{1}{0}'.format(n(x-1), lX)
return m[x]
像这样的东西可以满足你的需要。 以它为例,看看你的方法有什么不同之处。在
结果:
^{pr2}$要处理大于9的整数,可以尝试如下操作:
这是一个基本的递归解决方案。{{1}可能不需要使用回文结构,但只需要使用一次回文结构:
这将使用字符串格式来组合递归情况下的结果。递归调用的结果重复两次,因为格式字符串引用
{0}
两次。在相关问题 更多 >
编程相关推荐