获取输入整数并返回回文的递归模式

2024-04-20 04:37:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个整数来创建一个类似的结果:

pattern(0)
0
pattern(1)
010
pattern(2)
0102010
pattern(3)
010201030102010
and so forth....

输出必须是一个字符串,并像上面一样打印在一行上。 我假设我需要使用某种类型的递归方法和范围函数,但是如果没有硬编码,就无法通过模式(2)。如果有人能为我指出正确的方向,我将不胜感激。在


Tags: and方法函数字符串类型编码so模式
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))

结果:

^{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]

这是一个基本的递归解决方案。{{1}可能不需要使用回文结构,但只需要使用一次回文结构:

def reflected_palindrome(n):
    if n == 0:
        return "0" # base case

    return "{0}{1}{0}".format(reflected_palindrome(n-1), n)

这将使用字符串格式来组合递归情况下的结果。递归调用的结果重复两次,因为格式字符串引用{0}两次。在

相关问题 更多 >