Python Fibonacci Generator

2019-01-06 20:10发布

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 following:

a = int(raw_input('Give amount: '))

def fib():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

a = fib()
a.next()
0
for i in range(a):
    print a.next(),

15条回答
啃猪蹄的小仙女
2楼-- · 2019-01-06 20:35

It looks like you are using the a twice. Try changing that to a different variable name.

The following seems to be working great for me.

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a+b

f = fib()
for x in range(100):
    print(f.next())
查看更多
Juvenile、少年°
3楼-- · 2019-01-06 20:39

Also you can use enumerate infinite generator:

for i,f  in enumerate(fib()):
    print i, f
    if i>=n: break
查看更多
Viruses.
4楼-- · 2019-01-06 20:44

Here's how to do it with n = 50. You can of course replace the 50 by user input

def fibo():
    yield 1
    yield 1
    formerOfFormer = 1
    former = 1
    while True:
        newVal = formerOfFormer + former
        formerOfFormer = former
        former = newVal
        yield newVal


generator = fibo()
for i in xrange(50):
    print generator.next()
查看更多
登录 后发表回答