zoukankan      html  css  js  c++  java
  • 迭代器构造斐波那契数列

    # class Fei(object):
    # def __init__(self,n):
    # self.n = n
    # self.num1 = 0
    # self.num2 = 1
    # self.current = 0
    #
    # def __iter__(self):
    # return self
    #
    # def __next__(self):
    # if self.current < self.n:
    # num = self.num1
    # self.num1,self.num2 = self.num2,self.num1+self.num2
    # self.current += 1
    # return num
    # else:
    # raise StopIteration
    #
    # if __name__ == '__main__':
    # fei = Fei(20)
    # while True:
    # try:
    # print(next(fei),end=" ")
    # except StopIteration:
    # break

    class Fei(object):
    def __init__(self,n):
    self.num1 = 0 # 第一个初始值
    self.num2 = 1 # 第二个初始值
    self.current = 0 # 代表下标,记录位置
    self.n = n # 构造长度为n的斐波那契数列

    def __iter__(self):
    """返回自身"""
    return self

    def __next__(self):
    """获取下一个位置元素"""
    if self.current < self.n:
    num = self.num1 # 用一个变量临时保存初始值0
    self.num1,self.num2 = self.num2, self.num1+self.num2 # 构造斐波那契数列下一个值
    self.current += 1 # 构造一次位置变更一次
    return num
    else:
    raise StopIteration # 超出长度跑出停止迭代异常

    if __name__ == '__main__':
    fei = Fei(10)
    for i in fei:
    print(i,end=" ")

    # def fei(n):
    # num1,num2 = 0,1
    # current = 0
    # while current < n:
    # num = num1
    # num1,num2 = num2,num1+num2
    # current += 1
    # yield num
    # else:
    # raise StopIteration
    #
    # if __name__ == '__main__':
    # f = fei(10)
    # for i in f:
    # print(i)

    # print(list(f))


    # while True:
    # try:
    # print(next(f),end=" ")
    # except StopIteration:
    # break

  • 相关阅读:
    asp.net 对母版页的控件事件
    treeview操作集合
    使用GAppProxy时安全证书无效的解决办法
    向Excel模板中添加数据
    C# 重写 winform 关闭按钮
    完整ASP.Net Excel导入程序(支持2007)
    随笔二则
    标记枚举(flags)的使用
    System.Reflection.Missing.Value与Type.Missing
    Windows下Android源码下载方法
  • 原文地址:https://www.cnblogs.com/daizhonglin/p/13453202.html
Copyright © 2011-2022 走看看