# Werden wir Helden für einen Tag

Home | About | Archive

# Afraid of Recursion

Posted on Mar 23, 2011 by Chung-hong Chan

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


Powered by Jekyll and profdr theme