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

Simple way to print Fibonacci series till n number

def Fib(n):
    i=a=0
    b=1
    while i<n:
        print (a)
        i=i+1
        c=a+b
        a=b
        b=c




Fib(input("Please Enter the number to get fibonacci series of the Number :  "))
查看更多
等我变得足够好
3楼-- · 2019-01-06 20:32

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)))
查看更多
三岁会撩人
4楼-- · 2019-01-06 20:33

To get the fibonacci numbers till any number (100 in this case) with generator, you can do this.

def getFibonacci():
    a, b = 0, 1

    while True:
        yield b
        b = a + b
        a = b - a

for num in getFibonacci():
    if num > 100:
        break
    print(num)
查看更多
做个烂人
5楼-- · 2019-01-06 20:33

I've build this a while ago:

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

fab = [0, 1, 1]
def fab_gen():
    while True:
        fab.append(fab[-1] + fab[-2])
        yield fab[-4]

fg = fab_gen()
for i in range(a): print(fg.next())

No that fab will grow over time, so it isn't a perfect solution.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-06 20:34

You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well

a, b = b, a + b #### should be a,b = a+b,a #####

`###yield a`
查看更多
Lonely孤独者°
7楼-- · 2019-01-06 20:35

Your a is a global name so-to-say.

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

Whenever Python sees an a, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.

查看更多
登录 后发表回答