chainsawriot

Home | About | Archive

Afraid of Recursion

Posted on Mar 23, 2011 by Chung-hong Chan

就算上完一大輪 CS 堂,我對 Recursion 的認知仍是半桶水,明顯不及 Iteration 。
當要我去理解一些有 Recursion 的 code ,就會覺得好驚,更加別說要將問題化解成 Recursion 能夠解決的樣子。
很想去克服恐懼,就是要多下苦功。看書中的 example code 是明的,例如這個。 ((取自 how to think like a computer scientist))

def countdown(n):
    if n < = 0:
        print 'Blastoff!'
    else:
        print n
        countdown(n-1)

Recursion 應該要有兩個重要的部份,就是 base case 和 simplifying algorithm 。以上的碼, n < = 0 就是 base case 。而 n-1 就是 simplifying algorithm 。以上的都不難明。
但是以下的東西就難明了。

def generate_all_subsets(s):
    "Return a sequence containing all the substrings of the string s."
    # print 'from start again'
    if len(s) == 0:
        # print 'blast!'
        return [""]
    # Include every subset of the elements that doesn't contain s[0]...
    # print 'S:'+str(s)
    subsets = generate_all_subsets(s[1:])
    # print 's[1:]:'+str(s[1:])
    # print 'subsets'
    # print subsets
    ans = subsets[:]
    # print 'enter'
    # ...and every subset that does (these are generated by adding s[0] to
    # every subset of the previously generated sequence).
    for subset in subsets:
        # print 'subset:'+str(subset)
        # print 's0 + subset:'+str(s[0]+subset)
        ans.append(s[0] + subset)
        # print 'ans'
        # print ans
    return ans

是別人寫的,目的是輸入一個 String ,卻會回報此 String 的所有 substring 。例如輸入 abc ,應該會回報 a, b, c, ab, bc 和 abc 。
我加入了大量的 print statement 去看看這個東西怎樣運作,有些成效,不過仍然有點一頭霧水。我發現理解 recursion 的最大困境是這東西很難 hand simulation ,我不能畫個 table 去理解。


Powered by Jekyll and profdr theme