Python Fibonacci Generator

前端 未结 17 1330
别那么骄傲
别那么骄傲 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:38

    I would use this method:

    Python 2

    a = int(raw_input('Give amount: '))
    
    def fib(n):
        a, b = 0, 1
        for _ in xrange(n):
            yield a
            a, b = b, a + b
    
    print list(fib(a))
    

    Python 3

    a = int(input('Give amount: '))
    
    def fib(n):
        a, b = 0, 1
        for _ in range(n):
            yield a
            a, b = b, a + b
    
    print(list(fib(a)))
    

提交回复
热议问题