Python 斐波那契生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3953749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:32:48  来源:igfitidea点击:

Python Fibonacci Generator

pythonfibonaccinaming-conventions

提问by John

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:

我需要制作一个程序,要求打印斐波那契数字的数量,然后将它们打印为 0、1、1、2……但我无法让它工作。我的代码如下所示:

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

回答by unutbu

You are giving atoo many meanings:

你给出了a太多的含义:

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 ain 10 lines of code!):

如果您为变量提供更具描述性的名称(a在 10 行代码中名称的 3 种不同用法!),您就不会遇到问题(通常如此):

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

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

并更改range(a)range(amount).

回答by Jungle Hunter

Your ais a global name so-to-say.

可以说你a是一个全球性的名字。

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.

每当 Python 看到 时a,它就会认为你在谈论上面的那个。将其称为其他东西(在其他地方或此处)应该会有所帮助。

回答by appusajeev

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.

Python 是一种动态类型语言。变量的类型是在运行时确定的,它可以随着执行的进行而变化。在这里,您首先声明了一个保存整数类型,后来又为它分配了一个函数,因此它的类型现在变成了一个函数。

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.

您正在尝试将“ a”作为参数应用于range()函数,该函数需要一个 int arg,但实际上您提供了一个函数变量作为参数。

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

这会起作用

回答by Martijn

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 fabwill grow over time, so it isn't a perfect solution.

不,它fab会随着时间的推移而增长,所以它不是一个完美的解决方案。

回答by rubik

I would use this method:

我会使用这种方法:

Python 2

蟒蛇 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

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

回答by Tony Veijalainen

Also you can use enumerate infinite generator:

您也可以使用枚举无限生成器:

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

回答by Patrick Krecker

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

您也可以尝试封闭形式的解决方案(由于舍入/溢出错误,无法保证非常大的 n 值):

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

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

回答by John La Rooy

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

既然你正在编写一个生成器,为什么不使用两个 yields 来节省做额外的 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

.....

.....

回答by Jeremy

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 的语句。您的收益声明也应该在您的掉期之后

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

a, b = b, a + b ####应该 a,b = a+b,a #####

`###yield a`

回答by Alex

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