寒假打卡第二十天,当前mit6.100L进度(16/26) 今天依然是补一下递归作业。
递归,递归!胡不归?
无基例之故,何以层层自缠?
递归,递归!胡不止?
栈溢连连作祟,终陷无穷循环!
以下两题是我在这门课的作业觉得挺有意思的两题。
1、L是一个包含小写字母的非空列表,编写一个递归函数返回其在字母表最靠前的字母。
python">def f(L):""" L is a non-empty list of lowercase letters.Returns the letter earliest in the alphabet. """if len(L) == 1:return L[0]else:if L[0] < f((L[1:])):return L[0]else:return f(L[1:])print(f(['z', 'a', 'b', 'c', 'd'])) # should print 'a'
2、L是一个列表,e是一个整数,编写一个递归函数返回e在L中出现的次数,包括L里的子列表。
python">def h(L, e):""" L is list, e is an intReturns a count of how many times e occurrs in L or (recursively) any sublist of L"""if len(L) == 0:return 0else:if type(L[0])==int:if L[0] == e:return 1+h(L[1:], e)else:return h(L[1:], e)elif type(L[0])== list:if e in L[0]:return h(L[0], e)+h(L[1:], e)else:return h(L[1:], e)print(h([1,2,[3],1], 1)) # should print 2
print(h([1,2,[3,1,[1,[1]]]], 1)) # should print 4