[TIL] Recursion 2

Jene Hojin Choi·2021년 2월 8일
0

Algorithm

목록 보기
3/17
post-thumbnail

Recursion

1. Find minimum value

Iterative solution

def find_min(my_list):
  min = None
  for element in my_list:
    if not min or (element < min):
      min = element
  return min

Recursive solution

def find_min(my_list, min = None):
  if not my_list:
    return min

  if not min or my_list[0] < min:
    min = my_list[0]
  return find_min(my_list[1:], min)

2. Find if it's palindrome

Iterative solution

def is_palindrome(my_string):
  string_length = len(my_string)
  middle_index = string_length // 2
  for index in range(0, middle_index):
    opposite_character_index = string_length - index - 1
    if my_string[index] != my_string[opposite_character_index]:
      return False  
  return True

Recursive solution

def is_palindrome(my_string):
    if len(my_string) == 0:
        return True
    if my_string[0] != my_string[-1]:
        return False
    my_string = my_string[1:len(my_string)-1]
    return is_palindrome(my_string)

3. Multiplication

Iterative solution

def multiplication(num1, num2):
  result = 0
  for count in range(0, num2):
    result += num1
  return result

Recursive solution

def multiplication(num1, num2):
    if num1 == 0 or num2 == 0:
        return 0
    return num1 + multiplication(num1, num2 - 1)

print(multiplication(3, 7))

0개의 댓글