这是我的Fib squence迭代器:

class fibo:

  def __init__(self, n=0):
     self.n = n
     self.x1 = 0
     self.x2 = 1

  def next(self):
      if self.n == 0:
          raise StopIteration
      else:
          self.n = self.n -1
          tmp = self.x1
          self.x1, self.x2 = self.x2, self.x1 + self.x2
          return tmp

  def __iter__(self):
      return self

结果是
>>> [i for i in fibo(15)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

如何修改代码,使连续调用不迭代前n个Fibonacci数,而是迭代后n个数,例如????
>>> f=fibo(5)

>>> [i for i in f]
[0, 1, 1, 2, 3]

>>> [i for i in f]
[5, 8, 13, 21, 34]
>>> [i for i in f]
[55, 89, 144, 233, 377]
>>> [i for i in f]
[610, 987, 1597, 2584, 4181]

最佳答案

这在2.7中有效

class fibo:

    def __init__(self, n=0):
        self.n = n
        self.x1 = 0
        self.x2 = 1
        self.current = 0 #We won't decrease n, but instead increase current until it
                             #Equals n

    def next(self):
        if self.n == self.current:
            self.current = 0
            raise StopIteration
        else:
            self.current +=1
            tmp = self.x1
            self.x1, self.x2 = self.x2, self.x1 + self.x2
            return tmp

    def __iter__(self):
        return self

f = fibo(5)
print [i for i in f]
print [i for i in f]

输出
[0, 1, 1, 2, 3]
[5, 8, 13, 21, 34]

08-28 02:39