Skip to content

Commit 7d1ad1f

Browse files
authored
Merge pull request powerexploit#15 from rootbid/add
Add recursion, powerexploit#1
2 parents 87ab84d + c84d115 commit 7d1ad1f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Scripts/recursion.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# "Towers of Hanoi" Game
2+
# A recursive solution almost forces itself on the programmer,
3+
# while the iterative solution of the game is hard to find and to grasp.
4+
#
5+
# "Recursion"
6+
# Recursion is a method of programming or coding a problem,
7+
# in which a function calls itself one or more times in its body.
8+
# Usually, it is returning the return value of this function call.
9+
# If a function definition satisfies the condition of recursion, we call this function a recursive function.
10+
11+
12+
def hanoi(n, source, helper, target):
13+
if n > 0:
14+
# move tower of size n-1 to helper:
15+
hanoi(n-1, source, target, helper)
16+
# move disk from source to target:
17+
if source:
18+
target.append(source.pop())
19+
# move tower of size n-1 from helper to target:
20+
hanoi(n-1, helper, source, target)
21+
22+
if __name__ == "__main__":
23+
height = int(input("Enter the height of the tower: "))
24+
source = [disk for disk in range(1, height+1)]
25+
helper = []
26+
target = []
27+
print("Before calling the recursive function...")
28+
print("Source tower: ", str(source))
29+
print("Target tower: ", str(target))
30+
31+
# call the hanoi function to start recursie execution
32+
hanoi(height, source, helper, target)
33+
print("After recursive calls...")
34+
print("Source tower: ", str(source))
35+
print("Target tower: ", str(target))

0 commit comments

Comments
 (0)