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

yipeiwu_com5年前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基础语法(Python基础知识点)

Python与Perl,C和Java语言等有许多相似之处。不过,也有语言之间有一些明确的区别。本章的目的是让你迅速学习Python的语法。 第一个Python程序: 交互模式编程: 调用...

python中hasattr()、getattr()、setattr()函数的使用

python中hasattr()、getattr()、setattr()函数的使用

 引言:   在阅读源码时,有很多简写的形式,其中一个比较常用的就是getattr()用来调用一个类中的变量或者方法,相关联的hasattr()、getattr()、setat...

Python_LDA实现方法详解

LDA(Latent Dirichlet allocation)模型是一种常用而用途广泛地概率主题模型。其实现一般通过Variational inference和Gibbs Sampin...

用python实现英文字母和相应序数转换的方法

第一步:字母转数字 英文字母转对应数字相对简单,可以在命令行输入一行需要转换的英文字母,然后对每一个字母在整个字母表中匹配,并返回相应的位数,然后累加这些位数即可。过程中,为了使结果更...

python 实现插入排序算法

复制代码 代码如下: #!/usr/bin/python def insert_sort(array): for i in range(1, len(array)): key = arr...