麻省理工学院公开课:计算机科学及编程导论习题3上

习题1:

写两个函数,分别叫calledcountSubStringMatch(使用迭代计数关键词)和countSubStringMatchRecursive(使用递归计数关键词);

必须按照下面方式定义。

def countSubStringMatch(target,key):

def countSubStringMatchRecursive(target, key):


def countSubStringMatch(target, key):
	count = 0
	order = 0
	while target.find(key, order) != -1:
		order = target.find(key, order) + 1
		count = count + 1
	return count
	

from string import find
		
def countSubStringMatchRecursive(target, key):
	count = 0
	if find(target, key) == -1:
		return count
	else:
		order = find(target, key) + 1
		count = countSubStringMatchRecursive(target[order:], key) + 1
		return count

递归不是很直觉,感觉非常蛋疼。


习题2:

写一个函数subStringMatchExact,返回找到关键词的起始位置的元组。

按照下面方式定义。

def subStringMatchExact(target,key)

from string import find
		
def subStringMatchExact(target, key):
	tuple = ()
	order = 0
	while find(target, key, order) != -1:
		tuple = tuple + (find(target, key, order),)
		order = find(target, key, order) + 1
	return tuple
		
target1 = 'atgacatgcacaagtatgcat'
target2 = 'atgaatgcatggatgtaaatgcag'

key10 = 'a'
key11 = 'atg'
key12 = 'atgc'
key13 = 'atgca'

print subStringMatchExact(target1, key10)
print subStringMatchExact(target1, key11)
print subStringMatchExact(target1, key12)
print subStringMatchExact(target1, key13)

print subStringMatchExact(target2, key10)
print subStringMatchExact(target2, key11)
print subStringMatchExact(target2, key12)
print subStringMatchExact(target2, key13)


target = raw_input("Please enter a target. ")
key = raw_input("Please enter a key word. ")

print subStringMatchExact(target, key)


第八行,我原本用的  order = find(target, key, order) + len(key)

但如果是"aaabb"中找"aa",那这样就会错过从1开始"aa";而且如果key为空的话会死循环...





你可能感兴趣的:(麻省理工学院公开课:计算机科学及编程导论习题3上)