Python走楼梯问题解决方法示例
作者:wanlifeipeng 时间:2021-07-07 22:57:51
本文实例讲述了Python走楼梯问题解决方法。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*-
#!python3
'''
下楼问题。从楼上走到楼下共有h个台阶,每一步有两种走法:
走1个台阶,走2个台阶,问有多少可走的方案。用递归思想和迭代思想编程
'''
'''
分析:问题可以从最后一次是走1步还是两步,反向考虑
'''
def take_stairs_recursive(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return take_stairs_recursive(n-1)+take_stairs_recursive(n-2)
'''
其实就是斐波那契数列
'''
def take_stairs(n):
if n == 1:
return 1
if n == 2:
return 2
a,b = 1,2
result = 0
for i in range(3,n+1):
result = a + b
a = b
b = result
return result
print(take_stairs_recursive(10))
print(take_stairs(10))
运行结果:
89
89
希望本文所述对大家Python程序设计有所帮助。
来源:http://www.cnblogs.com/hupeng1234/p/6680631.html
标签:Python,走楼梯问题,解决方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python变量赋值机制踩坑记录
2021-08-19 08:59:44
![](https://img.aspxhome.com/file/2023/6/92196_0s.png)
Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)
2021-01-23 04:23:13
Python3实现的判断回文链表算法示例
2021-04-10 05:53:25
Python操作MySQL模拟银行转账
2022-05-19 21:23:11
使用keras实现densenet和Xception的模型融合
2022-04-15 19:17:01
![](https://img.aspxhome.com/file/2023/1/77901_0s.jpg)
Go Gin实现文件上传下载的示例代码
2023-06-21 15:11:13
python3.5绘制随机漫步图
2022-08-12 14:16:13
![](https://img.aspxhome.com/file/2023/6/86246_0s.jpg)
python获取Pandas列名的几种方法
2022-10-31 09:29:27
Python中关键字is与==的区别简述
2022-07-09 10:32:09
python利用pytesseract 实现本地识别图片文字
2021-03-08 19:20:34
浅谈Python中带_的变量或函数命名
2023-08-30 15:44:08
与 Function 和 Object 相关的有趣代码
2010-05-07 12:29:00
![](https://img.aspxhome.com/file/UploadPic/20105/7/javascript_object_layout-52s.jpg)
Python正则表达中re模块的使用
2023-10-11 03:38:22
python线性插值解析
2021-07-01 21:31:17
![](https://img.aspxhome.com/file/2023/7/82947_0s.jpg)
实现用python算法计算圆周率的小诀窍
2023-10-16 15:16:27
![](https://img.aspxhome.com/file/2023/0/124740_0s.png)
Python操作PDF实现制作数据报告
2022-05-09 21:41:51
![](https://img.aspxhome.com/file/2023/9/121069_0s.png)
python基础教程项目三之万能的XML
2022-09-22 05:33:25
python入门之井字棋小游戏
2021-12-11 11:35:36
![](https://img.aspxhome.com/file/2023/2/123632_0s.jpg)
jupyter 中文乱码设置编码格式 避免控制台输出的解决
2023-04-27 08:01:13
![](https://img.aspxhome.com/file/2023/1/86241_0s.jpg)
Python 处理数据的实例详解
2021-05-31 21:29:35