def factorial_iterative(n): """ Returns the factorial of n, iteratively :param n: (num) the number to calculate its factorial :return: (num) n! """ num = 1 for i in range(2, n + 1): num *= i # same as num = num * i return num def factorial_iterative2(n): """ Returns the factorial of n, iteratively, in an alternative implementation :param n: (num) the number to calculate its factorial :return: (num) n! """ num = 1 for i in range(n): num *= (i + 1) # same as num = num * i return num def factorial(n): """ Returns the factorial of n, recursively :param n: (num) the number to calculate its factorial :return: (num) n! """ # check the base case if n == 1: return 1 else: # the recursive case return n * factorial(n - 1) def rec_sum(n): """ Calculates the sum of all numbers from 1 to n :param n: (positive int) the num to calculate the sum up to :return: (int) the sum from 1 to n """ if n == 0: return 0 else: return n + rec_sum(n-1) def rec_sum_list(some_list): """ Calculates the sum of all numbers in some_list :param some_list: (list) a list of numbers :return: (int) the sum of all the numbers in the list """ if some_list == []: return 0 else: return some_list[0] + rec_sum_list(some_list[1:]) def rec_sum_list_print(some_list): """ Calculates the sum of all numbers in some_list and prints the intermediate steps of the recursion :param some_list: (list) a list of numbers :return: (int) the sum of all the numbers in the list """ print("Calling rec_sum_list: " + str(some_list)) if some_list == []: print("base case returning 0") return 0 else: answer = some_list[0] + rec_sum_list_print(some_list[1:]) print(str(some_list) + " returning " + str(answer)) return answer def reverse(some_string): """ Returns the reverse of some_string :param some_string: (str) the string to reverse :return: (str) the reversed string """ if some_string == "": return "" else: return reverse(some_string[1:]) + some_string[0] def reverse_print(some_string): """ Returns the reverse of some_string and prints the intermediate steps of the recursion :param some_string: (str) the string to reverse :return: (str) the reversed string """ print("calling " + some_string) if some_string == "": print("return base ") return "" else: answer = reverse_print(some_string[1:]) + some_string[0] print("returning " + answer) return answer def power(base, exponent): """ Returns base^exponent :param base: (num) the base :param exponent: (num) the exponent :return: (num) base^exponent """ if exponent == 0: return 1 else: return base * power(base, exponent - 1)