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 kth paragraph for which select returns True. If no such paragraph exists (because k is too large), then choose returns the empty string.

Problem analysis:

1. Pay attention to the requirement to return the Kth paragraph that satisfies the select function.

2. If the length of the paragraph array that satisfies the selection is exceeded, an empty string is returned ('') 

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.

 You can take a closer look at the function in utils.py. It is the key to solving this problem:

1. Use the lower function to change both judgment objects to lowercase.

2. Use the remove_punctuation function to remove the punctuation in the paragraph.

3. Use the split function to divide the paragraphy into words


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

Problem 6 (2 pts)

Implement shifty_shifts, which is a diff function that takes two strings. It returns the minimum number of characters that must be changed in the start word in order to transform it into the goal word. If the strings are not of equal length, the difference in lengths is added to the total.

Here are some examples:

>>> big_limit = 10
>>> shifty_shifts("nice", "rice", big_limit)    # Substitute: n -> r
1
>>> shifty_shifts("range", "rungs", big_limit)  # Substitute: a -> u, e -> s
2
>>> shifty_shifts("pill", "pillage", big_limit) # Don't substitute anything, length difference of 3.
3
>>> shifty_shifts("roses", "arose", big_limit)  # Substitute: r -> a, o -> r, s -> o, e -> s, s -> e
5
>>> shifty_shifts("rose", "hello", big_limit)   # Substitue: r->h, o->e, s->l, e->l, length difference of 1.
5

If the number of characters that must change is greater than limit, then shifty_shifts should return any number larger than limit and should minimize the amount of computation needed to do so.

These two calls to shifty_shifts should take about the same amount of time to evaluate:

>>> limit = 4
>>> shifty_shifts("roses", "arose", limit) > limit
True
>>> shifty_shifts("rosesabcdefghijklm", "arosenopqrstuvwxyz", limit) > limit
True

Important: You may not use while or for statements in your implementation. Use recursion.

Before writing any code, unlock the tests to verify your understanding of the question.

1. Question analysis (note the red letters):

1. If the length is different, add the length difference directly.

2. If the initials are different, add one

3. Question (if the number of recursions exceeds the limit, return directly):

        ​ ​ 1. There is an increased value greater than the limit (equivalent to the value obtained by backtracking is already greater than the limit)

        ​ ​ 2. There is no increased value greater than the limit, and the recursion continues

2. Answer code:

        below

def shifty_shifts(start, goal, limit):
    """A diff function for autocorrect that determines how many letters
    in START need to be substituted to create GOAL, then adds the difference in
    their lengths.
    """
    # BEGIN PROBLEM 6
    end_diff=0
    if len(start)!=len(goal):
        end_diff,min_len=abs(len(start)-len(goal)),min(len(start),len(goal))
        start=start[0:min_len]
        goal=goal[0:min_len]

    if len(start) ==0:
        return 0

    # 判断首位字母(可以代替if - else)
    end_diff+=int(start[0] != goal[0])

    # 存在增加的数值大于限制(相当于回溯得到的值已经大于limit)
    if end_diff>limit:
        return end_diff
    # 不存在增加的数值大于限制,就继续深度递归
    return end_diff+shifty_shifts(start[1:],goal[1:],limit-end_diff)

Guess you like

Origin blog.csdn.net/2301_79140115/article/details/134953427