Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Recursion

Back


Recursion 递归


Factorial function


Factorial function in Python:

def fact(n):
    '''
    Returns factorial of n (n!).
    Note use of recursion
    '''
    # BASE CASE!
    if n == 0:
        return 1

    # Recursion!
    else:
        return n * fact(n-1)

Summary


Problems

Problems

Cumulative Sum

Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer

For example, if n=4 , return 4+3+2+1+0, which is 10.

This problem is very similar to the factorial problem presented during the introduction to recursion. Remember, always think of what the base case will look like. In this case, we have a base case of n =0 (Note, you could have also designed the cut off to be 1).

In this case, we have: n + (n-1) + (n-2) + …. + 0

Fill out a sample solution:

def rec_sum(n):
    pass

sum of all digits

Given an integer, create a function which returns the sum of all the individual digits in that integer. For example:

def sum_func(n):
    pass

Split string into words

Note, this is a more advanced problem than the previous two! It aso has a lot of variation possibilities and we’re ignoring strict requirements here.

Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is completely splittable.


def word_split(phrase, list_of_words, output=None):
    pass

word_split('themanran', ['the', 'ran', 'man'])


Memoization


Implement memoization in Python

# encapsulate the memoization process into a class:
# 创建一个类, 该类的实例将会存储一个函数和字典
# 调用该实例时, 将先在字典中查找其参数; 如果没有则计算并存储在字典;如果有则直接返回其值.
class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}
    def __call__(self, *args):
        if not args in self.memo:
            self.memo[args] = self.f(*args)
        return self.memo[args]

# factorial function
def factorial(k):

    if k < 2:
        return 1

    return k * factorial(k - 1)

# create an instance of memoization
# 此时factorial是被重写, 但之前的定义匿名存储在Memoize的实例属性f中.
factorial = Memoize(factorial)

print(factorial(3))     # 6


Problems

Practice


Further Reading

http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html

https://www.quora.com/Why-is-tail-recursion-optimisation-not-implemented-in-languages-like-Python-Ruby-and-Clojure-Is-it-just-difficult-or-impossible


TOP