【问题标题】:The value none is being returned Fibonacci sequence返回值 none 斐波那契数列
【发布时间】:2020-02-29 03:19:51
【问题描述】:

我完全不明白为什么我的代码没有返回任何内容。我是新手,已经找了一段时间了,还是迷路了。

class Fibonacci:

    def __init__(self, max = 0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max: # if n is less that 0
            def FIB(number):
                if number == 1 or number == 2:
                    return 1
                else:
                    return FIB(number - 1) + FIB(number - 2)
            self.n += 1
        else:
            raise StopIteration

【问题讨论】:

  • 您永远不会调用您定义的FIB 函数。在self.n += 1 行下方,添加return FIB(self.n)
  • 你在调用什么代码返回None。除了 dunder 之外,我没有看到任何其他方法?
  • @rafaelc 谢谢!我盯着这个看的时间比我应该看到的要长。

标签: python oop fibonacci


【解决方案1】:

每次调用__next__ 时,您的实现都会花费越来越多的时间。应该使用迭代方法而不是迭代的复杂性:

class Fibonacci:

    def __init__(self, max = 0):
        self.max = max
        self.a = 0
        self.b = 1

    def __iter__(self):
        self.a = 0
        self.b = 1
        return self

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b
        if self.a <= self.max: # if n is less that 0
            return self.a
        else:
            raise StopIteration

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2012-10-12
    • 2011-08-10
    • 2013-03-29
    • 2015-06-05
    • 2016-05-24
    相关资源
    最近更新 更多