python编码-斐波那契

1

    def __init__(self):
        self.a,self.b = 0 ,1  # 初始化两个计数器a,b

    def __iter__(self):  # 实例本身就是迭代对象,故返回自己
        return self

    def __next__(self):
        self.a,self.b = self.b,self.a+self.b  # 计算下一个值
        if self.a > 100:                # 退出循环的条件
            raise StopIteration()
        return self.a               # 返回下一个值

for n in Fib():
    print(n)

2.单个输出第t个数

def fib(num):

    a,b,c=1,1,0
    if num <=0:
        print ('wrong')
    if num > 0 and num <= 2:
        print ('1')
    else:
        while num > 2:
            a,b =b,a+b
            num = num-1
        print (b)
            
    return 0

t = 3
fib(t)

注意:a,b = b,a+b相当于(a,b)= (b,a+b)

3.从第一位输出直到第n个数

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'

>>> fib(6)
1
1
2
3
5
8
'done'

你可能感兴趣的:(python编码-斐波那契)