python - 递归错误 : maximum recursion depth exceeded in comparison Python

标签 python recursion

我正在尝试编写一个递归函数来在 python 中打印某种排列。 但是由于某种原因我得到了最大深度错误。

def perm(chars, k, word):
   if k == 0:
      print(word)
   for char in chars:
      perm(chars, k - 1, char + word)


perm(['1','2'], 2, '')

有人知道错误是什么吗?

最佳答案

您缺少一个 base case ,导致您的调用堆栈为 overflow .通过使 for 循环(递归情况)成为条件来添加基本情况:

def perm(chars, k, word):
   if k == 0:
       print(word)
   else:
       for char in chars:
           perm(chars, k - 1, char + word)


perm(['1','2'], 2, '')

输出:

11
21
12
22

Try it!

关于python - 递归错误 : maximum recursion depth exceeded in comparison Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325713/

相关文章:

python minidom : 'NoneType' object has no attribute 'data' from url

java - 找到搜索结果时抛出异常

node.js - 在 Node.js 中,我如何使用集合作为索引以编程方式从 Redis 数据库中检索许多哈希

c# - 无法实现数组均值的递归方法

Java长时间运行程序递归导致的StackOverflowError

python - 如何构建可以从任何站点提取特定信息的网络爬虫?

python - 如何使用 pycogent 在 python 2.7 中创建祖先序列?

python - 如何使用 Refinitiv Eikon API 检索指定交易所 RIC 的所有关联公司 RIC?

javascript - 从字符串键检索和连接深度嵌套数组的递归方法

python - 如何从Python中不同类型的日期中提取年份