by Albert Major
0! = 1.n! = n * (n-1)!.Factorial Example:
Recursive solution:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Iterative solution:
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Tower of Hanoi:
Problem: Move all disks from one pole to another with rules:
Recursive solution:
n-1 disks to the intermediate pole.n-1 disks from the intermediate pole to the target pole.Example code:
def hanoi(n, start, end, temp):
if n == 0:
return
hanoi(n - 1, start, temp, end)
print(f"Move disk {n} from {start} to {end}")
hanoi(n - 1, temp, end, start)
Exercises: