<分区>
我需要创建一个接受单个整数并返回类似于以下结果的函数:
pattern(0)
0
pattern(1)
010
pattern(2)
0102010
pattern(3)
010201030102010
and so forth....
输出必须是一个字符串,并且像上面一样打印在一行中。 我假设我需要使用某种类型的递归方法和范围函数,但如果不进行硬编码就无法通过 pattern(2) 。如果有人能指出我正确的方向,非常感谢。
<分区>
我需要创建一个接受单个整数并返回类似于以下结果的函数:
pattern(0)
0
pattern(1)
010
pattern(2)
0102010
pattern(3)
010201030102010
and so forth....
输出必须是一个字符串,并且像上面一样打印在一行中。 我假设我需要使用某种类型的递归方法和范围函数,但如果不进行硬编码就无法通过 pattern(2) 。如果有人能指出我正确的方向,非常感谢。
最佳答案
像这样的东西可以满足您的需要。 以它为例,看看您的方法有何不同。
#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))
结果:
0
010
0102010
010201030102010
0102010301020104010201030102010
要处理大于 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]
关于python - 递归模式获取输入整数并返回回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25410752/