【问题标题】:Python function return None. Why? [duplicate]Python 函数返回无。为什么? [复制]
【发布时间】:2013-09-29 17:58:55
【问题描述】:
count = []

def problem14(n):
    count.append(n)
    if n == 1:
        return count
    if n % 2 == 0:
        n = n/2
        problem14(n)
    else:
        n = 3*n + 1
        problem14(n)


print problem14(13)

这是我写的代码。我不知道为什么它返回 None 而在我看来它应该返回列表'count'。有什么帮助吗?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    使用递归的时候还需要return语句,否则返回值会丢失:

    def problem14(n):
        count.append(n)
        if n == 1:
            return count
        if n % 2 == 0:
            n = n/2
            return problem14(n)  # <--
        else:
            n = 3*n + 1
            return problem14(n)  # <--
    

    顺便说一句,这可能是 Project Euler #14 的错误方法 :-) 考虑改用 dynamic programming 方法(为了不破坏乐趣,我会这么说)。

    【讨论】:

      【解决方案2】:

      您应该使用 return 关键字来 return 来自函数的值。

      return problem14(n)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2022-07-22
        • 1970-01-01
        • 2012-12-01
        • 2017-10-21
        相关资源
        最近更新 更多