From Fibonacci Sequence to Tower of Hanoi: Recursive Thoughts in Programming Python Learning Mathematics

The idea of recursion in programming refers to a method of solving problems that uses functions to call their own characteristics and decompose a complex problem into smaller sub-problems until the sub-problems can be solved directly. The advantage of recursion is that it can make the code concise and clear, and it is suitable for solving some problems that are recursive in nature, such as tree traversal, Tower of Hanoi, depth-first search of graphs, etc. The disadvantage of recursion is that it may cause stack overflow, be inefficient, or be difficult to understand and debug.

To write a recursive function, you usually need the following steps:

? Define a base case: Identify the simplest case for which the solution to the problem is known or obvious. This is the terminating condition of recursion because it prevents the function from calling itself infinitely.

? Define a recursive case: define the problem into smaller sub-problems. Break the problem into smaller versions and call functions recursively to solve each sub-problem.

? Ensure that recursion terminates: Ensure that the recursive function eventually reaches the base case and does not enter an infinite loop.

? Combination solution: Combining solutions to subproblems to solve the original problem.

The Fibonacci sequence is a famous mathematical sequence in which each item is the sum of the previous two items, as shown below:

1, 1, 2, 3, 5, 8, 13, 21, 34, …

The Fibonacci sequence has many interesting properties and applications, such as its relationship to the golden ratio, and its occurrence in nature, such as the arrangement of fruits in pineapples, the number of petals in sunflowers, rabbit reproduction, etc.

To generate the Fibonacci sequence using programming, we can use the idea of recursion. First, we need to define a function that accepts a parameter n, indicating that the nth Fibonacci number is required. Then, we have to consider two situations:

? Basic case: When n is 0 or 1, the nth Fibonacci number is n itself. This is the simplest case, and we can directly return n as the result.

? Recursive situation: When n is greater than 1, the nth Fibonacci number is the sum of the n-1th term and the n-2th term. This is a smaller sub-problem that we can use the function itself to solve. And add the results and return them.

Implement this function in Python as follows:

def fab(n):` `if n<1:` `print("Incorrect input")` `return -1`` if n==1 or n==2:` `return 1 ` `else:` `return fab(n-1) + fab(n-2)``result=fab(12)``if result!=-1:` `print(f"There are {result} pairs in total The birth of a little rabbit")

This function is a recursive function that calls itself to solve the subproblem. We can use this function to calculate any Fibonacci number, for example:

result=fab(12)``if result!=-1:``print(f"A total of {result} pairs of little bunnies were born")

Output:

A total of 144 pairs of bunnies were born

Tower of Hanoi is a classic puzzle game, which consists of three pillars and several discs of different sizes. When the game starts, all discs are stacked on the first pillar in order from largest to smallest. The object of the game is to move all discs to the third pillar and keep the original order. The rules of the game are that only one disk can be moved at a time, and the big disk cannot be placed on top of the small disk.

The Tower of Hanoi game looks simple, but actually requires many steps to complete. To use programming to simulate the Tower of Hanoi game, we can also use recursive ideas. First, we need to define a function that accepts four parameters: n represents the number of discs, x represents the starting pillar, y represents the auxiliary pillar, and z represents the target pillar. Then, we have to consider two situations:

? Basic case: when n is 1, there is only one disk, we can move it directly from x to z and print out the steps of the move.

? Recursive situation: When n is greater than 1, we can divide the problem into three steps:

? Moving n-1 disks from x to y, using z as an auxiliary pillar, is a smaller sub-problem that we can solve using the function itself.

? Move the largest disk from x to z and print out the steps of the move.

? Move n-1 disks from y to z, using x as an auxiliary pillar. This is also a smaller sub-problem that we can solve using the function itself.

Implement this function in Python as follows:

def hanoi(n,x,y,z):` `if n==1:` `print(x,"-->",z)` `else:` `hanoi(n-1 ,x,z,y)` `print(x,"-->",z)` `hanoi(n-1,y,x,z)``hanoi(4,"Tower X", "Tower Y","Tower Z")

This function is also a recursive function that calls itself to solve subproblems. We can use this function to simulate the Tower of Hanoi game with any number of discs, for example:

hanoi(4,"Tower X","Tower Y","Tower Z")

Output:

Tower X --> Tower Y``Tower X --> Tower Z``Tower Y --> Tower Z``Tower X --> Tower Y``Tower Z --> Tower X``Tower Z --> Tower Y `` Tower X --> Tower Y `` Tower X --> Tower Z `` Tower Y --> Tower Z `` Tower Y --> Tower X `` Tower Z --> Tower X ``Tower Y --> Tower Z `` Tower X --> Tower Y `` Tower X --> Tower Z `` Tower Y --> Tower Z

Through the above two examples, we can see how the idea of recursion is applied in programming. Recursion has the following characteristics and advantages:

? Recursion can decompose a complex problem into smaller sub-problems, thereby simplifying the structure and logic of the problem.

? Recursion can make the code more concise and clear, avoiding the use of complex control structures such as loops and multiple conditional judgments.

? Recursion can be suitable for solving some problems that are recursive in nature, such as tree traversal, graph search, combination arrangement, etc.

Of course, recursion also has some drawbacks and challenges:

? Recursion consumes more memory and time resources, because each time a function is called, the function’s state and parameters need to be saved on the stack, and repeated calculations may occur.

? Recursion needs to pay attention to designing the basic situation and recursion situation, and ensuring that the recursion can be terminated, otherwise it may lead to errors such as infinite loops or stack overflows.

? Recursion is sometimes difficult to understand and debug because it involves multiple levels of function calls and returns.

Therefore, when using recursion, we need to weigh the pros and cons and choose the appropriate method based on the specific problem and needs. In short, recursion is a very powerful and elegant programming idea that allows us to use computer language to describe and solve various problems.

Gallery:


———————————END——————- ——–

Digression

In the current era of big data, how can one keep up with the times without mastering a programming language? Python, the hottest programming language at the moment, has a bright future! If you also want to keep up with the times and improve yourself, please take a look.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.