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

标签 python algorithm recursion

<分区>

我需要创建一个接受单个整数并返回类似于以下结果的函数:

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/

相关文章:

java - 坚持理解递归

python - 在没有扩展名的情况下在 Python 中读取文件

python - 引用与 Python 中的局部变量同名的全局变量

algorithm - 具有两个不同参数的嵌套循环的时间复杂度

用于基于范围的无线传感器网络 (WSN) 定位的 Java 观察者模式

c++ - 从 num1 到 num2 的最短路径(在 C++ 中)

parsing - ERLANG - 将列表拆分为子列表

python - 如何在 Keras 的每个训练时期之后进行预测?

python - 尝试获取两个附加值的字符串并将它们相减

algorithm - 有效处理 "update elements"和 "get min value among all element"查询