Untitled Document
Untitled Document
Beginner-Level Solutions
Factorial Calculation
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1)
Sum of Digits
def sum_digits(n):
if n == 0: # Base case
return 0
Count Down
def count_down(n):
return
print(n)
count_down(n - 1)
count_down(5) # Output: 5, 4, 3, 2, 1
Power Calculation
return 1
Check Palindrome
def is_palindrome(s):
return True
Intermediate-Level Solutions
Fibonacci Sequence
def fibonacci(n):
if n == 0 or n == 1: # Base cases
return n
if b == 0: # Base case
return a
return gcd(b, a % b)
Reverse a String
def reverse(s):
return s
Binary Search
return -1
return mid
arr = [1, 2, 3, 4, 5, 6]
if n == 1: # Base case
return
# Output:
Permutations of a String
print("".join(s))
s_copy = [c for c in s]
permutations(s_copy, step + 1)
permutations(list("abc"))
11.
Recursive Sum
def recursive_sum(lst):
Path in a Maze
return False
if (x, y) in path:
return False
path.append((x, y))
return True
path.append((x, y))
path.pop()
return False
maze = [
[1, 0, 0],
[1, 1, 0],
[0, 1, 1]
path = []
is_path(maze, 0, 0, path)
Recursive Flattening
def flatten(lst):
if not lst:
return []
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
else:
12.
N-Queens Problem
if len(board) == n:
print(board)
return
row = len(board)
continue
solve_n_queens(n, board + [col], col_set |
{col}, diag1_set | {row - col}, diag2_set | {row +
col})
solve_n_queens(4)