【问题标题】:Python different output when casting the recursive call with str function使用 str 函数转换递归调用时 Python 不同的输出
【发布时间】:2022-01-15 17:48:03
【问题描述】:

我希望结果是字符串类型,所以我尝试使用 str 函数强制递归调用

当返回类型 int 的结果时,下面的函数可以正常工作

def factor(n: int) -> int:
    if n <= 1:
        return 1
    return n * factor(n - 1)


print("factorial 5=", factor(5))

输出:

factorial 5= 120

但是当递归调用 str str(n * factor(n - 1)) 时,我得到了不同的结果

def factor(n: int) -> str:
    if n <= 1:
        return 1
    return str(n * factor(n - 1))


print("factorial 5=", factor(5))

输出:

factorial 5= 222222222222222222222222222222222222222222222222222222222222

我做错了什么?

【问题讨论】:

  • 因为你在各个层面都进行了演员,不仅在最后返回
  • return n * factor(n - 1) 的逻辑只有在 factor(n - 1) 是 int 而不是字符串时才有意义。所以你不希望递归调用返回字符串。

标签: python recursion casting


【解决方案1】:

递归依赖于使用 int 参数递归调用。因此,您需要像

这样的包装器
def factor(n: int) -> str:
    def factor_internal(n: int):
        if n <= 1:
            return 1
        return n*factor_internal(n - 1)
    
    return str(factor_internal(n))


print("factorial 5=", factor(5))

在您的实现中,乘法 n*factor(n-1) 是整数 n 与字符串 factor(n-1) 的乘法。在 Python 中,这会导致字符串串联,n-times。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2021-04-21
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多