Skip to content
This repository was archived by the owner on Nov 30, 2022. It is now read-only.

Add recursion, ankitdobhal/Python-Scripts#1 #15

Merged
merged 1 commit into from
Oct 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Scripts/recursion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# "Towers of Hanoi" Game
# A recursive solution almost forces itself on the programmer,
# while the iterative solution of the game is hard to find and to grasp.
#
# "Recursion"
# Recursion is a method of programming or coding a problem,
# in which a function calls itself one or more times in its body.
# Usually, it is returning the return value of this function call.
# If a function definition satisfies the condition of recursion, we call this function a recursive function.


def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n-1 to helper:
hanoi(n-1, source, target, helper)
# move disk from source to target:
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target:
hanoi(n-1, helper, source, target)

if __name__ == "__main__":
height = int(input("Enter the height of the tower: "))
source = [disk for disk in range(1, height+1)]
helper = []
target = []
print("Before calling the recursive function...")
print("Source tower: ", str(source))
print("Target tower: ", str(target))

# call the hanoi function to start recursie execution
hanoi(height, source, helper, target)
print("After recursive calls...")
print("Source tower: ", str(source))
print("Target tower: ", str(target))