This article mainly introduces Python's method of solving the problem of N-level steps, briefly describes the problem of walking steps, and analyzes the related operating skills of Python using recursive and recursive algorithms to solve the problem of walking steps in the form of examples. It needs Friends can refer to
This article describes how Python solves the problem of N steps. Share it with everyone for your reference. The details are as follows:
Question: There are N steps in a building. The rabbit can jump 1, 2 or 3 steps each time. How many ways are there in total?
Afanty's analysis:
When you encounter this kind of problem of finding rules, just push and push yourself. How many moves are there at level 1? How many moves are there at level 2? How many moves are there at level 3? How many moves are there at level 4? How many moves are there at level 5?
Right, the rules are out!
Error-prone points: This is not a combination problem, because walking on level 1 for the first time and level 2 for the second time is different from walking on level 2 for the first time and level 1 for the second time.
The following is the recursive implementation code of 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
Of course, it can also be implemented using non-recursive methods. The following is the code based on the recursive method:
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
Okay, the above is the process implemented using the recursive and recursive methods respectively. .
Related recommendations:
subprocess batch execution of linux commands in python
The above is the detailed content of Python's method to solve the problem of N-order steps. For more information, please follow other related articles on the PHP Chinese website!