""" Some recursive functions """ # David Kauchak # 11/14/2011 def factorial_iterative(n): """ Returns the factorial of n, iteratively """ num = 1 for i in range(2, n+1): num *= i return num def factorial(n): """ Returns the factorial of n, recursively """ # check the base case if n == 0: return 1 else: # the recursive case return n * factorial(n-1) def factorial_interesting(n): """ a one-line way of calculating factorial. it's not recursive, but kind of cool :) """ return eval(str(range(2,n+1))\ .replace('[',"")\ .replace(']',"")\ .replace(", ", "*")) def reverse(some_string): """ Returns the reverse of the input string """ if len(some_string) == 0: return "" else: temp = some_string[-1] + reverse(some_string[:-1]) print "Returning: " + temp return temp def power(base, exponent): """ Returns the base^exponent """ if exponent == 0: return 1 else: return base * power(base, exponent-1) def fast_power(base, exponent): """ Returns the base^exponent """ if exponent == 0: return 1 elif exponent % 2 == 0: # b^e = b^(e/2) * b^(e/2) temp = fast_power(base, exponent/2) return temp * temp else: return base * fast_power(base, exponent-1)