Python Fibonacci Generator

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

    Since you are writing a generator, why not use two yields, to save doing the extra shuffle?

    import itertools as it
    
    num_iterations = int(raw_input('How many? '))
    def fib():
        a,b = 0,1
        while True:
            yield a
            b = a+b
            yield b
            a = a+b
    
    for x in it.islice(fib(), num_iterations):
        print x
    

    .....

提交回复
热议问题