Skip to content

Commit c84d115

Browse files
committed
Add recursion, powerexploit#1
1 parent e8d3bf7 commit c84d115

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy