【问题标题】:How do I implement recursion to this python program我如何实现这个 python 程序的递归
【发布时间】:2022-12-03 02:19:39
【问题描述】:
def recurse( aList ):
    matches = [ match for match in action if "A" in match ]
    uses = " ".join(matches)
    return f"Answer: { aList.index( uses )"

这是非递归方法。我只是不知道如何在列表方面实现递归。 输出应该是Answer: n uses. 任何人都可以帮忙。

【问题讨论】:

  • aList 的值是什么样的?它(可能)是嵌套列表吗?
  • aList = ["Eat", "Eat.Run", "Play.", "Drive.A"]
  • 所以在这种情况下输出应该是3 uses

标签: python python-3.x list recursion


【解决方案1】:

递归不适合 Python 中的这个问题,因为列表并不是真正的递归数据结构。但是您可以编写以下内容:

def recurse(aList):
   if not aList:
       return 0
   return ("A" in aList[0]) + recurse(aList[1:])

根据定义,空列表中的任何内容都不包含 "A"。否则,确定 "A" 是否在列表的第一个元素中,并根据需要将 1 或 0 添加到列表其余部分的匹配项数(请记住,bools 在 Python 中是 ints)。

递归函数应该只处理计数本身;让递归函数的调用者将计数放入一个字符串中:

print("Answer: {recurse(aList)} uses"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 2011-10-23
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多