from HanoiUI import Application:
class Hanoi(Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def hanoi_recursive(self, n, a, b, c):
if n == 1:
# If there is only one piece, just move it. No recursion needed
self.move(self.top_disk(a), a, b)
return
# Use recursion here to move the n-1 piece from a to b using c
# This line moves the piece from a to b
self.move(self.top_disk(a), a, b)
# Use recursion here to move the n-1 piece from c to a using b
def hanoi_iterative(self, n, a, b, c):
def move_next_piece(a, b):
A = self.top_disk(a)
B = self.top_disk(b)
if A > B:
self.move(B, b, a)
else:
self.move(A, a, b)
if not (n % 2 == 0):
b, c = c, b
comb = (2 ** n) - 1
for i in range(comb):
if i % 3 == 0:
move_next_piece(a, b)
elif i % 3 == 1:
move_next_piece(a, c)
elif i % 3 == 2:
move_next_piece(b, c)
return
What is recursion?
Recursion is calling a function inside of itself multiple times until it reaches a base case.
What is iteration?
Iteration is utilizing a loop to repeat instructions until a termination case is met.
When do you use recursion over iteration?
Recursion can be used to make the code shorter when time complexity (runtime) is not an issue.
When do you use iteration over recursion?
Iteration can be used to make time complexity(runtime) shorter in exchange for longer code.
Does recursion and iteration give the same results?
Recursion and iteration give the same results when solving the same problem.
BONUS: Do you think they run at the same speed?
Iteration runs a bit faster than recursion if
the number of recursive calls is large.
Project written by Patience Lamb.