Python Fibonacci Generator

删除回忆录丶 提交于 2019-11-26 08:27:40

问题


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(),

回答1:


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)))



回答2:


You are giving a too many meanings:

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

vs.

a = fib()       

You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name a in 10 lines of code!):

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

and change range(a) to range(amount).




回答3:


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

.....




回答4:


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.




回答5:


Also you can use enumerate infinite generator:

for i,f  in enumerate(fib()):
    print i, f
    if i>=n: break



回答6:


Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):

root5 = pow(5, 0.5)
ratio = (1 + root5)/2

def fib(n):
    return int((pow(ratio, n) - pow(1 - ratio, n))/root5)



回答7:


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`



回答8:


def fibonacci(n):
    fn = [0, 1,]
    for i in range(2, n):
        fn.append(fn[i-1] + fn[i-2])
    return fn



回答9:


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 :  "))



回答10:


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)



回答11:


Python is a dynamically typed language. the type of a variable is determined at runtime and it can vary as the execution is in progress. Here at first, you have declared a to hold an integer type and later you have assigned a function to it and so its type now became a function.

you are trying to apply 'a' as an argument to range() function which expects an int arg but you have in effect provided a function variable as argument.

the corrected code should be

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

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

b = fib()
b.next()

for i in range(a):
    print b.next(),

this will work




回答12:


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.




回答13:


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())



回答14:


i like this version:

array = [0,1]

for i in range(20):
   x = array[0]+array[1]   
   print(x)
   array[0] = array[1]
   array[1] = x



回答15:


def genFibanocciSeries():

    a=0
    b=1
    for x in range(1,10):
        yield a
        a,b = b, a+b

for fib_series in genFibanocciSeries():
    print(fib_series)



回答16:


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)


来源:https://stackoverflow.com/questions/3953749/python-fibonacci-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!