def factorial_iter(n): '''Returns the factorial of n using iteration.''' answer = 1 for i in range(1, n + 1): answer *= i return answer def factorial(n): '''Returns the factorial of n using recursion.''' print('computing {0}!'.format(n)) if n == 0: print('I know the factorial of 0!') return 1 else: answer = factorial(n - 1) * n print('computed {0}! = {1}'.format(n, answer)) return answer def strlen_iter(some_string): '''Return the length of some_string without using len.''' count = 0 for next_char in some_string: count += 1 return count def strlen(some_string): '''Recursively return the length of some_string.''' print('I want the length of {0}'.format(some_string)) if some_string == '': # base case: no recursive call print('the empty string has length 0') return 0 else: # recursive case answer = 1 + strlen(some_string[1:]) print('the length of {0} is {1}'.format(some_string, answer)) return answer def num_digits(num): '''Return the number of digits in (non-negative) num.''' print('I want the number of digits in {0}'.format(num)) if num < 10: print('base case: num digits of {0} is 1'.format(num)) # base case return 1 else: # recursive case answer = 1 + num_digits(num / 10) print('recursive: num digits of {0} is {1}'.format(num, answer)) return answer def power(base, n): '''Return base raised to the power n.''' if n == 0: return 1 else: return base * power(base, n - 1)