# python uses recursion to deal with problems

```Today we're going to use recursion, Fibonacci sequence, and print file hierarchy
```

, Hanoi Tower Games.

```Recursion is a kind of method of function calling itself. No one says that it's a dead cycle to call itself. We need to set our own end conditions. I personally think that recursion thinking you only need to clarify the beginning and end conditions. Most of them are calling themselves again and again.
First, let's look at Fibonacci sequence. First, we use the idea of recursion to print:
```
```def fab(n):
a = 0
b = 1
while n > 0:

if a == 0 or b == 1:
print(1,end= ' ')
a, b = b, a + b
n -= 1
else:
print(b, end= ' ')
a, b = b, a + b
n -= 1
//Let's print it5Fibonacci series within:
fab(10)
G:\python\python.exe G:/Pyproject/day115/test3.py
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Process finished with exit code 0
```

We are using recursion to print Fibonacci series:

```def fab(n):
if n == 2 or n == 1:
return 1
else:
return fab(n - 1) + fab(n - 2)

for i in range(1, 21):
print(fab(i), end= ' ')

//We print Fibonacci series within 20
G:\python\python.exe G:/Pyproject/day115/test3.py
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Process finished with exit code 0```

Next, we use recursion to realize the printing of the directory structure level of the printing file. Let's first solve the problem with circulation:

```import os
def get_all(path):

temp = [path]
while len(temp):
new_path = temp.pop()
L = os.listdir(new_path)
for name in L:
new_name = os.path.join(new_path, name)
if os.path.isdir(new_name):
print('catalog:', new_name)
temp.append(new_name)
else:
print('File:', new_name)

//See the results:
G:\python\python.exe G:/Pyproject/day115/test2.py

Process finished with exit code 0
```

Then we use recursive implementation:

```import os

def get_all(path):
L = os.listdir(path)

for name in L:
new_path = os.path.join(path, name)
if os.path.isdir(new_path):
print('catalog:', new_path)
get_all(new_path)
else:
print('File:', new_path)

//The results are:
G:\python\python.exe G:/Pyproject/day115/test2.py

Process finished with exit code 0```

Finally, let's take a look at the Hanoi tower game:

```def hanoi(n, x, y, z):
if n == 1:
print(x, ' --> ', z)
else:
hanoi(n-1, x, z, y) # Move the first n-1 plates from x to y
print(x, ' --> ', z) # Move the bottom last plate from x to z
hanoi(n-1, y, x, z) # Move n-1 plates on y to z

n = int(input('Please enter the number of floors of Hanoi Tower:'))
hanoi(n, 'X', 'Y', 'Z')

//There are three columns x y z, and the arrow points to indicate where to transfer from
//Let's enter three to see the execution result:
//Please enter the number of floors of Hanoi Tower:3
X  -->  Z
X  -->  Y
Z  -->  Y
X  -->  Z
Y  -->  X
Y  -->  Z
X  -->  Z

Process finished with exit code 0
```

Tags: Python

Posted on Fri, 01 May 2020 22:49:39 -0700 by Liquix