以下代码中运用了字典功能,用于计算文本中字符串出现的频率;其中{}代表创建一个可填入的dictionary,类似于array
# Insert your completed FrequencyMap() function here.
def FrequencyMap(Text, k):
# your code here
freq = {}#代表字典
n = len(Text)
for i in range(n-k+1):
Pattern = Text[i:i+k]
if Pattern in freq:
freq[Pattern]+=1
else:
freq[Pattern]=1
# hint: your code goes here!
return freq
values()内置函数,用于返回dictionary 中含有的值
m=max(freq.values())#返回频率最大的值
def FrequentWords(Text, k):
words = []#代表列表
freq = FrequencyMap(Text, k)
m = max(freq.values())
for key in freq:
# add each key to words whose corresponding frequency value is equal to m
if freq[key]==m:
pattern=key
words.append(pattern)# 如需将项目添加到列表的末尾,请使用 append() 方法
return words
# your code here
for key in freq:
# add each key to words whose corresponding frequency value is equal to m return words