Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pasted my solutions to recursion problems #217

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
31 changes: 28 additions & 3 deletions part-1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,42 @@
# the appropriate comment.

# factorial

def factorial(n):
if n < 0:
raise ValueError("Number must be positive")
if n == 0:
return 1

return factorial(n-1) * n


# reverse
def reverse(text):
if not text or len(text) == 1:
return text

first = text[0]
last = text[-1]
return last + reverse(text[1:-1]) + first


# bunny

def bunny(count):
if not count:
return 0
if count == 1:
return 2
return bunny(count-1) + 2


# is_nested_parens

def is_nested_parens(parens):
if not parens:
return True
elif parens[0] == ")" or parens[-1] == "(":
return False
else:
is_inner_nested = parens[1:-1]
return is_nested_parens(is_inner_nested)


26 changes: 25 additions & 1 deletion part-2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,37 @@
# the appropriate comment.

# search

def search(array, query):
if not array:
return False
elif array[0] == query:
return True

return search(array[1:], query)


# is_palindrome
def is_palindrome(text):
if len(text) == 3 or len(text) == 2:
return text[0] == text[-1]

return is_palindrome(text[1:-1])


# digit_match
def digit_match(num_1, num_2):
# Base case: we're at the beginning of the num
if num_1 < 10 or num_2 < 10:
if num_1 % 10 == num_2 % 10:
return 1
else:
return 0

# Recursive case
if num_1 % 10 == num_2 % 10:
return 1 + digit_match(num_1 // 10, num_2 // 10)
else:
return digit_match(num_1 // 10, num_2 // 10)