每次写代码,LZ感觉还是得自己手敲一遍。。。一遍?一遍哪够?看着别人现成的代码觉得自己都能看的懂,等到自己上手解决自己任务的时候,才发现根本不是这么一回事。看了很多大神的博客,基本上都有一颗强大的内心,为啥?码了那么久的代码,结果一个bug就可能前功尽弃,从头再来,也是只能默默鼓励下自己:每天进步一点点!
"""Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
import re
listOfTokens = re.split(r'\W*', s)
# print (listOfTokens)
ss = set(listOfTokens)
# print (ss)
bow = [0] * len(ss)
ll = list(ss)
for word in listOfTokens:
if word in ss:
bow[ll.index(word)] += 1
dd = {}
for i in range(len(ss)):
dd[ll[i]] = bow[i]
# sort_dd = sorted(dd.items(), key = lambda asd:asd[1], reverse = True)
sort_dd = sorted(dd.items(), key = lambda asd:(-asd[1], asd[0]))
top_ll = dict(sort_dd[0:n])
top_n = top_ll.keys()
# TODO: Return the top n most frequent words.
return top_n
def test_run():
"""Test count_words() with some inputs."""
print (count_words("cat bat mat cat bat cat", 3))
print (count_words("betty bought a bit of butter but the butter was bitter", 3))
if __name__ == '__main__':
test_run()
test_run()
代码量不大,但是对于python入门的新手任务来说还是有挑战的O(∩_∩)O