Project 2: CS 61A Autocorrected Typing Software
Problem 1 (1 pt)
Implement?choose
, which selects which paragraph the user will type. It takes a list of?paragraphs
?(strings), a?select
?function that returns?True
?for paragraphs that can be selected, and a non-negative index?k
. The?choose
?function return's the?k
th paragraph for which?select
?returns?True
. If no such paragraph exists (because?k
?is too large), then?choose
?returns the empty string.
问题解析:
1.注意要求返回满足select函数的第K个段落
2.超出满足select的段落数组长度,返回空字符串('')?
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
list_paragraph=[]
select_cot=0
for paragraph in paragraphs:
if select(paragraph):
list_paragraph.append(paragraph)
select_cot+=1
if k>=select_cot:
return ''
return list_paragraph[k]
# END PROBLEM 1T
?
Problem 2 (2 pt)
Implement?about
, which takes a list of?topic
?words. It returns a function which takes a paragraph and returns a boolean indicating whether that paragraph contains any of the words in?topic
. The returned function can be passed to?choose
?as the?select
?argument.
To make this comparison accurately, you will need to ignore case (that is, assume that uppercase and lowercase letters don't change what word it is) and punctuation.
Assume that all words in the?topic
?list are already lowercased and do not contain punctuation.
Hint: You may use the string utility functions in?
utils.py
.
?可以仔细看看utils.py
.里的函数,是解决本题的关键:
1.利用lower函数将两个判断的对象均改为小写
2.利用remove_punctuation函数将paragraph里的标点去掉
3.利用split函数将paragraphy分为一个个单词
def about(topic):
"""Return a select function that returns whether a paragraph contains one
of the words in TOPIC.
>>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
'Cute Dog!'
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
'Nice pup.'
"""
assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
def select(paragraph):
for topic_element in topic:
if lower(topic_element) in split(remove_punctuation(lower(paragraph))):
return True
return False
return select
# END PROBLEM 2
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!