如何在 Python 中将斐波那契数列打印到第 n 个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15820601/
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
How do I print a fibonacci sequence to the nth number in Python?
提问by Al GoRhythm
I have a homework assignment that I'm stumped on. I'm trying to write a program that outputs the fibonacci sequence up the nth number. Here's what I have so far:
我有一个家庭作业,我很难过。我正在尝试编写一个程序,输出第 n 个数字的斐波那契数列。这是我到目前为止所拥有的:
def fib():
n = int(input("Please Enter a number: "))
if n == 1:
return(1)
elif n == 0:
return(0)
else:
return (n-1) + (n-2)
mylist = range[0:n]
print(mylist)
I'm thinking I could use separate functions but I can't figure out how to pass the argument that calculates the fibonacci sequence. Then the next step would be to to print out the sequence of numbers up to that number.
我想我可以使用单独的函数,但我不知道如何传递计算斐波那契数列的参数。然后下一步是打印出直到该数字的数字序列。
采纳答案by J0HN
Non-recursive solution
非递归解决方案
def fib(n):
cur = 1
old = 1
i = 1
while (i < n):
cur, old, i = cur+old, cur, i+1
return cur
for i in range(10):
print(fib(i))
Generator solution:
发电机解决方案:
def fib(n):
old = 0
cur = 1
i = 1
yield cur
while (i < n):
cur, old, i = cur+old, cur, i+1
yield cur
for f in fib(10):
print(f)
Note that generator solution outperforms the non-recursive (and non-recursive outperforms recursive, if memoization is not applied to recursive solution)
请注意,生成器解决方案优于非递归(并且非递归优于递归,如果记忆未应用于递归解决方案)
One more time, recursive with memoization:
再一次,通过记忆递归:
def memoize(func):
memo = dict()
def decorated(n):
if n not in memo:
memo[n] = func(n)
return memo[n]
return decorated
@memoize
def fib(n):
#added for demonstration purposes only - not really needed
global call_count
call_count = call_count + 1
#end demonstration purposes
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
call_count = 0 #added for demonstration purposes only - not really needed
for i in range(100):
print(fib(i))
print(call_count) #prints 100
This time eachfibbonacci number calculated exactlyonce, and than stored. So, this solution would outperform all the rest. However, the decorator implementation is just quick and dirty, don't let it into production. (see this amazing questionon SO for details about python decorators :)
这一次,每个fibbonacci数计算恰好一次,并存储比。因此,此解决方案将胜过所有其他解决方案。然而,装饰器实现只是快速而肮脏,不要让它投入生产。(有关 python 装饰器的详细信息,请参阅SO 上的这个惊人问题:)
So, having fibdefined, the program would be something like (sorry, just looping is boring, here's some more cool python stuff: list comprehensions)
所以,fib定义后,程序将类似于(抱歉,只是循环很无聊,这里有一些更酷的 Python 内容:列表理解)
fib_n = int(input("Fib number?"))
fibs = [fib(i) for i in range(fib_n)]
print " ".join(fibs)
this prints all numbers in ONE line, separated by spaces. If you want each on it's own line - replace " "with "\n"
这将打印一行中的所有数字,用空格分隔。如果您希望每个都在自己的行上 - 替换" "为"\n"
回答by karthikr
Please note, in your call
请注意,在您的通话中
- You are not calling fib() recursively
- You need a wrapper method so that the input is not requested every time the method is called recursively
- You do not need to send in a list. Just the number n is good enough.
- 你不是递归调用 fib()
- 您需要一个包装器方法,以便每次递归调用该方法时都不会请求输入
- 您不需要发送列表。只是数字 n 就足够了。
This method would only give you the nth number in the sequence. It does not print the sequence.
这种方法只会给你序列中的第 n 个数字。它不打印序列。
You need to return fib(n-1) + fib(n-2)
你需要 return fib(n-1) + fib(n-2)
def f():
n = int(input("Please Enter a number: "))
print fib(n)
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
回答by Joran Beasley
def fib(n):
if n == 1:
return(1)
elif n == 0:
return(0)
else:
return fib(n-1) + fib(n-2)
my_num = int(input("Enter a number:"))
print fib(my_num)
Im not really sure what your question is... but the answer is probably something like this
我不太确定你的问题是什么......但答案可能是这样的
回答by CornSmith
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(int(input())))
And since you want to print up to the nth number:
并且由于您想打印到第nth 个数字:
[print(fibonacci(n)) for n in range (int(input()))]
And for python2.7 change inputto raw_input.
而对于 python2.7 更改input为raw_input.
回答by Binayaka Chakraborty
Separate functions would be best, as the recursive function would be far easier to deal with. On the other hand, you could code an iterative function that would take only one parameter
最好是单独的函数,因为递归函数会更容易处理。另一方面,您可以编写一个只接受一个参数的迭代函数
Recursively::
递归::
def fib(n):
if n == 1:
return (1);
elif n == 0:
return (0);
else:
return fib(n-1) + fib(n-2);
def callFib():
n = int(raw_input('Enter n::\t'));
mylist = fib(n);
print mylist;
callFib();
Iteratively::
迭代::
def fib():
n = int(raw_input('Enter n::\t'));
terms = [0,1];
i=2;
while i<=n:
terms.append(terms[i-1] + terms[i-2]);
i=i+1;
print terms[n];
fib();
回答by user2095044
for a recursive solution:
对于递归解决方案:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
x=input('which fibonnaci number do you want?')
print fib(x)
explanation: if n is 0, then ofcourse the '0th' term is 0, and the 1st term is one. From here, you know that the next numbers will be the sum of the previous 2. That is what's inferred by the line after the else.
解释:如果 n 为 0,那么当然第 0 项为 0,第 1 项为 1。从这里,您知道下一个数字将是前两个数字的总和。这就是 else 之后的行推断出的。
回答by Adeel
This might be faster incase of long list
如果列表很长,这可能会更快
# Get nth Fibonacci number
def nfib(nth):
sq5 = 5**.5
phi1 = (1+sq5)/2
phi2 = -1 * (phi1 -1)
resp = (phi1**(nth+1) - phi2**(nth+1))/sq5
return long(resp)
for i in range(10):
print i+1, ": ", nfib(i)
OUTPUT
输出
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
6 : 8
7 : 13
8 : 21
9 : 34
10 : 55

