本文实例讲述了Python解决N阶台阶走法问题的方法。分享给大家供大家参考,具体如下:
题目:一栋楼有N阶楼梯,兔子每次可以跳1、2或3阶,问一共有多少种走法?
Afanty的分析:
遇到这种求规律的问题,自己动动手推推就好,1阶有几种走法?2阶有几种走法?3阶有几种走法?4阶有几种走法?5阶有几种走法?
对吧,规律出来了!
易错点:这不是组合问题,因为第1次走1阶、第2次走2阶不同于 第1次走2阶、第2次走1阶
下面是Python的递归实现代码:
def allMethods(stairs): ''''' :param stairs:the numbers of stair :return: ''' if isinstance(stairs,int) and stairs > 0: basic_num = {1:1,2:2,3:4} if stairs in basic_num.keys(): return basic_num[stairs] else: return allMethods(stairs-1) + allMethods(stairs-2) + allMethods(stairs-3) else: print 'the num of stair is wrong' return False
当然也可以用非递归的方法来实现,下面就是基于递推法的代码:
def allMethod(stairs): '''''递推实现 :param stairs: the amount of stair :return: ''' if isinstance(stairs,int) and stairs > 0: h1,h2,h3,n = 1,2,4,4 basic_num = {1:1,2:2,3:4} if stairs in basic_num.keys(): return basic_num[stairs] else: while n <= stairs: temp = h1 h1 = h2 h2 = h3 h3 = temp + h1 + h2 return h3 else: print 'the num of stair is wrong' return False
好的,以上就是分别用了递归和递推法实现的过程。
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《粤语超白金 百听不厌的经典金曲 2CD》[WAV/分轨][1.3GB]
- 群星.1994-全世界精丫华星】【WAV+CUE】
- 杜德伟.1997-知.解2CD【滚石】【WAV+CUE】
- 群星.2022-一不小心喵上你原声大碟【TME影音】【FLAC分轨】
- 《战锤40K星际战士2》卡在正在加入服务器解决方法
- 《勇者斗恶龙怪物仙境3》玩法内容介绍
- 《幸福工厂》无限报错解决方法
- 交错战线原始交易所推荐角色一览
- 战锤40K星际战士2战术职业介绍|战术职业技能效果一览
- 战锤40K星际战士2突击职业介绍|突击职业技能效果一览
- [妙音金曲]群星《悲情咖啡屋》(黑胶)2CD[DTS-WAV]
- 阿兰·达瓦卓玛《A-Lan阿兰唯美歌姬》2CD[DTS-WAV]
- 【小提琴】陈立新《思乡曲》2004[FLAC+CUE]
- 《战地》新作明年初大规模测试!EA已内部测试一年
- 《GTAOL》PC版时隔多年更新反作弊!小助手宣布跑路