斐波那契数,在Python 3中只有一线吗? [英] Fibonacci numbers, with an one-liner in Python 3?
问题描述
我知道用适当的函数结构编写没有什么问题,但是我想知道如何用最Python的方式用单行找到第n个斐波那契数.
I know there is nothing wrong with writing with proper function structure, but I would like to know how can I find nth fibonacci number with most Pythonic way with a one-line.
我编写了该代码,但是在我看来,这并不是最好的方法:
I wrote that code, but It didn't seem to me best way:
>>> fib = lambda n:reduce(lambda x, y: (x[0]+x[1], x[0]), [(1,1)]*(n-2))[0]
>>> fib(8)
13
怎么会更好,更简单?
推荐答案
fib = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]
(这将维护一个从[a,b]映射到[b,a + b]的元组,初始化为[0,1],迭代N次,然后获取第一个元组元素)
(this maintains a tuple mapped from [a,b] to [b,a+b], initialized to [0,1], iterated N times, then takes the first tuple element)
>>> fib(1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051
89040387984007925516929592259308032263477520968962323987332247116164299644090653
3187938298969649928516003704476137795166849228875L
(请注意,在此编号中,fib(0)= 0,fib(1)= 1,fib(2)= 1,fib(3)= 2,依此类推)
(note that in this numbering, fib(0) = 0, fib(1) = 1, fib(2) = 1, fib(3) = 2, etc.)
(还请注意:reduce
是Python 2.7中的内置功能,但不是Python 3中的内置功能;您需要在Python 3中执行from functools import reduce
.)
(also note: reduce
is a builtin in Python 2.7 but not in Python 3; you'd need to execute from functools import reduce
in Python 3.)
这篇关于斐波那契数,在Python 3中只有一线吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!