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

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

.....

查看更多
3楼-- · 2019-01-06 20:23

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

查看更多
Luminary・发光体
4楼-- · 2019-01-06 20:26

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

查看更多
仙女界的扛把子
5楼-- · 2019-01-06 20:26

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)
查看更多
太酷不给撩
6楼-- · 2019-01-06 20:26

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
查看更多
ら.Afraid
7楼-- · 2019-01-06 20:30
def fibonacci(n):
    fn = [0, 1,]
    for i in range(2, n):
        fn.append(fn[i-1] + fn[i-2])
    return fn
查看更多
登录 后发表回答