博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用graphviz模块展示斐波那契数列的递归函数调用图(Python)
阅读量:6937 次
发布时间:2019-06-27

本文共 1835 字,大约阅读时间需要 6 分钟。

  在博客中,在求解斐波那契数列的第n项时,我们采用了递归方法和动态规划法来求解,当然递归方法的效率很差。本文将利用graphviz模块来展示斐波那契数列的递归函数调用图。

  利用递归函数来求解斐波那契数列的第n项的Python代码如下:

# recursive methoddef fib(n):    if n <= 1:        return n    else:         return fib(n-1) + fib(n-2)t = fib(10)print(t)

  为了展示该递归方法的函数调用图,我们可以用graphviz模块来绘制该流程图。Graphviz (英文:Graph Visualization Software的缩写)是一个由AT&T实验室启动的开源工具包,用于绘制DOT语言脚本描述的图形。在Python中,它的实现模块为graphviz, 其API参考文档为: 。

  下面将给出n=6时递归函数的调用图, Python代码如下:

from graphviz import Digraphimport uuidimport random# colors for labels of nodescolors = ['tomato', 'skyblue', 'orange', 'purple', 'green', 'yellow', 'gray', 'pink']# n: the nth item in Fabonacci sequence# dot: Digraph object# label: label of each node# parent: label of parent nodedef fib(n, dot, label, parent):    if n <= 1:        return n, dot    else:        random.shuffle(colors)        # create node with style='filled' and random color        dot.node(label[0], 'fib(%s)'%(n-1),style='filled',color=colors[0])        dot.node(label[1], 'fib(%s)'%(n-2),style='filled',color=colors[1])        # connect the new created nodes with parent node        dot.edge(label[0], parent)        dot.edge(label[1], parent)        # generate new label using uuid() function        label1 = [str(uuid.uuid1()) for _ in label]        label2 = [str(uuid.uuid1()) for _ in label]        return fib(n-1, dot, label1, label[0])+fib(n-2, dot, label2, label[1]), dot# testdot = Digraph()n = 6 # the nth item in Fabonacci sequencelabel = ['a', 'b'] # initial labelst, dot = fib(n, dot, label, parent='fib(%s)'%n)# save the source code of dot to gv fileprint(dot.source)dot.render('E:\\fib_graph.gv')

  运行完上述程序后,会在E盘下生成fib_graph.gv文件,再用Graphviz软件打开,生成图片,如下:

n=6的递归函数调用图
  本次分享仅作为graghviz模块的一个例子,欢迎广大读者能提供更多例子~~
  本次分享到此结束,欢迎大家交流~~

注意:本人现已开通两个微信公众号: 用Python做数学(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

你可能感兴趣的文章
我的友情链接
查看>>
自动监控linux服务器负载并重启Web服务的脚本
查看>>
四、Windows Server 2012R2 Hyper-v虚拟交换机的创建与管理
查看>>
java 运算顺序
查看>>
天涯LVS部署
查看>>
eclipse不能自动编译工程的解决方法
查看>>
最好用的cisco路由模拟器 debianIOL
查看>>
Shpinx在PHPCMS里的使用及配置
查看>>
Linux Oracle Rac 10G 搭建& Patch
查看>>
django models.py模块的外部引用
查看>>
VMware虚拟化技术培训(8) 虚拟机管理之二
查看>>
spring内部各模块jar包依赖
查看>>
Apache与Nginx网络模型对比
查看>>
Java 二重循环实现对象去重
查看>>
Supporting Python 3(支持python3)——序
查看>>
从零开始-打造自己的虚拟实验室-2
查看>>
js 完美兼容浏览器的复制功能
查看>>
jdk1.6下使用sardine和jackrabbit-webdav的问题
查看>>
[Unity3d]socket通信 切换到web版本时报错SecurityException解决办法
查看>>
[Unity3D插件]2dtoolkit系列二 动画精灵的创建以及背景图的无限滚动
查看>>