This article example describes how Python solves the N-step step walk problem. Shared for your reference, as follows:
Question: A building has N stairs, and a rabbit can jump 1, 2 or 3 steps at a time, ask how many ways are there to walk?
Afanty's analysis:
When it comes to this kind of pattern problem, you can just move your hands and push yourself, how many ways are there to go in order 1, how many ways are there to go in order 2, how many ways are there to go in order 3, how many ways are there to go in order 4, how many ways are there to go in order 5, and how many ways are there to go in order 6?
Right? The law is out!
Error-prone points:It's not a matter of combinations, because going 1 step in the 1st and 2 steps in the 2nd is different from going 2 steps in the 1st and 1 step in the 2nd.
Here is the code for Python's recursion implementation:
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
Of course it can be done in a non-recursive way, here is the code based on the recursive method:
def allMethod(stairs): '''''recursive implementation :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
Well, the above is the process that has been implemented using recursion and recursion respectively.
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python encryption and decryption algorithms and techniques》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.