栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Python中将斐波那契序列打印到第n个数字?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Python中将斐波那契序列打印到第n个数字?

非递归解决方案

def fib(n):    cur = 1    old = 1    i = 1    while (i < n):        cur, old, i = cur+old, cur, i+1    return curfor i in range(10):    print(fib(i))

发电机解决方案:

def fib(n):    old = 0    cur = 1    i = 1    yield cur    while (i < n):        cur, old, i = cur+old, cur, i+1        yield curfor f in fib(10):    print(f)

请注意,生成器解决方案的性能优于非递归解决方案(并且,如果未将备忘录应用于递归解决方案,则非递归也优于递归)

再一次,通过记忆递归:

def memoize(func):    memo = dict()    def decorated(n):        if n not in memo: memo[n] = func(n)        return memo[n]    return decorated@memoizedef 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 neededfor i in range(100):    print(fib(i))print(call_count) #prints 100

这一次, 每个 fibbonacci数计算 恰好
一次,并存储比。因此,该解决方案将胜过所有其他解决方案。但是,装饰器的实现既快速又肮脏,请不要将其投入生产。(有关python装饰器的详细信息,请参见SO上的这个令人惊讶的问题:)

因此,

fib
定义后,该程序将类似于(对不起,只是循环很无聊,这是一些更酷的python东西:list
comprehensions

fib_n = int(input("Fib number?"))fibs = [fib(i) for i in range(fib_n)]print " ".join(fibs)

这会在一行中打印所有数字,并用空格分隔。如果您希望每条线都单独显示

" "
,请替换为
"n"



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464470.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号