Python Fibonacci Generator

前端 未结 17 1421
别那么骄傲
别那么骄傲 2020-11-27 20:59

I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can\'t get it to work. My code looks the followi

17条回答
  •  心在旅途
    2020-11-27 21:54

    Below are two solution for fiboncci generation:

    def fib_generator(num):
        '''
        this will works as generator function and take yield into account.
        '''
        assert num > 0
        a, b = 1, 1
        while num > 0:
            yield a
            a, b = b, a+b
            num -= 1
    
    
    times = int(input('Enter the number for fib generaton: '))
    fib_gen = fib_generator(times)
    while(times > 0):
        print(next(fib_gen))
        times = times - 1
    
    
    def fib_series(num):
        '''
        it collects entires series and then print it.
        '''
        assert num > 0
        series = []
        a, b = 1, 1
        while num > 0:
            series.append(a)
            a, b = b, a+b
            num -= 1
        print(series)
    
    
    times = int(input('Enter the number for fib generaton: '))
    fib_series(times)
    

提交回复
热议问题