如何使用递归来重复一个字符串?

新手上路,请多包涵

我已经被困在一个问题上一段时间了:

我正在寻找创建一个使用字符串和正整数的 python 函数。该函数将打印字符串 n 次,共 n 行。我 不能 使用循环,我只能使用递归

例如

>>> repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello

每当我尝试创建一个执行此操作的函数时,该函数都会逐渐减少字符串的长度:

例如

>>> repeat("hello", 3)
hellohellohello
hellohello
hello

这是我的代码的样子:

 def repeat(a, n):
    if n == 0:
        print(a*n)
    else:
        print(a*n)
        repeat(a, n-1)

这种尝试有什么问题?我该如何解决?

原文由 Andrew Louis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 250
2 个回答

尝试这个

def f(string, n, c=0):
    if c < n:
        print(string * n)
        f(string, n, c=c + 1)

f('abc', 3)

原文由 zyxue 发布,翻译遵循 CC BY-SA 3.0 许可协议

一个班轮

def repeat(a,n):
    print((((a*n)+'\n')*n)[:-1])

让我们把它分开

  1. a*n 重复字符串 n 次,这就是你想要的一行
  2. +'\n' 在字符串中添加一个新行,以便您可以转到下一行
  3. *n 因为你需要重复 n
  4. [:-1] 是删除最后一个 \n 因为 print 默认换行。

原文由 gokul_uf 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题