Python初学者递归

时间:2012-10-26 21:07:17

标签: python recursion

我正在尝试获取一个简单的函数,它接受n并打印

If n > 0:
    print((n*'*')+(n*'!'), end=' ')

尝试以递归方式获得相同的解决方案。我是递归的初学者,我经常得到“更高层次的思考”,但我无法理解必须遵循的代码。

我的基本情况是,当n为0时,它什么都不打印。当n大于1时,它将打印n份* + n份的副本!

def repeat(n):
    if n <= 0:
        pass
    else:
        repeat(n-1)
        print((n*'*')+(n*'!'), end=' ')

现在它打印n,然后连续打印n-1直到0.我尝试将其分解为两个打印语句并使用多个递归..但它变成了一个混乱的模式。

我也不允许使用循环。这个让我疯狂;除了简单的一行语句之外,我已经提出了几个解决方案,但没有一个使用递归。

5 个答案:

答案 0 :(得分:3)

如果你构建并返回一个字符串并将其打印在函数之外,它会更简单,如下所示:

def printPattern(n):
    if n <= 0:
        return ''
    return '*' + printPattern(n-1) + '!'

或者作为一个单行:

def printPattern(n):
    return '*' + printPattern(n-1) + '!' if n > 0 else ''

无论哪种方式,这都有效:

print printPattern(5)
> *****!!!!!

答案 1 :(得分:1)

假设您有n - 1的解决方案。前置*并附加!

def repeat(n):
    if n > 0:
        print("*", end=" ")
        repeat(n - 1)
        print("!", end=" ")

答案 2 :(得分:1)

以下是您想要的内容。

def repeat(n):
  def stars(n):
    return '*'+stars(n-1)+'!' if n > 0 else ''
  print stars(n)

例如,repeat(5)打印*****!!!!!repeat(8)打印件 ********!!!!!!!!

答案 3 :(得分:0)

我实际上并不知道你在问什么......如果有更高效或更好的方法吗?这很明显:

def repeat(n):
    if n >= 0:
        print((n*'*')+(n*'!'), end=' ')
        return repeat(n-1)

答案 4 :(得分:0)

我会在这里使用两个字符串,并在n<=0时返回这两个字符串的串联字符串,并使用return而不是在函数内打印:

def repeat(n, strs1="", strs2=""):     # The Default value of strings is ""

    if n <= 0:
        return strs1 + strs2   # if n<=0 then concatenate the two strings and return them
    else:
        strs1 += "*"          # Add * to strs1
        strs2 += "!"          # Add ! to strs2
        return repeat(n-1, strs1, strs2)  # Pass n-1, as well as the two strings to a recursive call

print(repeat(5))
print(repeat(3))

<强>输出:

*****!!!!!
***!!!