Python解决N阶台阶走法问题的方法分析

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python读文件逐行处理的示例代码分享

复制代码 代码如下:import os ## for os.path.isfile() def dealline(line) :    print(line...

通过PHP与Python代码对比的语法差异详解

一、背景 人工智能这几年一直都比较火,笔者一直想去学习一番;因为一直是从事PHP开发工作,对于Python接触并不算多,总是在关键时候面临着基础不牢,地动山摇的尴尬,比如在遇到稍微深入...

在Python中操作字典之clear()方法的使用

 clear()方法将删除字典中的所有项目(清空字典) 语法 以下是clear()方法的语法: dict.clear() 参数   &nbs...

在Python中处理时间之clock()方法的使用

 clock()方法返回当前的处理器时间,以秒表示Unix上一个浮点数。精度取决于具有相同名称的C函数,但在任何情况下,这是使用于基准Python或定时的算法函数。 在Wind...

python if not in 多条件判断代码

python if not in 多条件判断代码

百度作业帮提问: python if not in 多条件 判断怎么写 s = ['1','2'] 判断条件 sta = "12345" 正常的是这样的, if "1" not in s...