Question

In: Computer Science

# Let me define the function I use for testing.  Don't change this cell. def check_equal(x, y,...

# Let me define the function I use for testing.  Don't change this cell.

def check_equal(x, y, msg=None):

    if x == y:

        if msg is None:

            print("Success")

        else:

            print(msg, ": Success")

    else:

        if msg is None:

            print("Error:")

        else:

            print("Error in", msg, ":")

        print("    Your answer was:", x)

        print("    Correct answer: ", y)

    assert x == y, "%r and %r are different" % (x, y)

## Problem 1: common word pairs

The goal is to find the set of consecutive word pairs in common between two sentences.

We will get there in steps, guiding you to the solution.

# First, notice that .split() splits a sentence according to white space, returning a list.

print("I love eating bananas".split())

# Second, recall that in Python, a[i:k] gives you the sub-list of a consisting

# of a[i], a[i+1], ..., a[k-1].

a = "I love eating bananas".split()

print(a[2:4])

### Problem 1 part 1: generating the list of consecutive words in a sentence.

You are given a sentence, with words separated by white space. You need to write a function `word_pairs` that outputs the list of consecutive words. For example, if the input is:

"I love eating bananas"
  
Then the function `word_pairs` should output:

[("I", "love"), ("love", "eating"), ("eating", "bananas")]
  
If the input sentence consists of fewer than two words, then `word_pairs` should output the empty list.
**Be careful:** the result should be a list of tuples, not a list of lists.

def word_pairs(sentence):

    # YOUR CODE HERE

# Base cases.  5 points.

check_equal(word_pairs(" "), [])

check_equal(word_pairs("woohoo"), [])

check_equal(word_pairs("I am"), [("I", "am")])

def common_word_pairs(sentence1, sentence2):

    """Returns the set of common consecutive word pairs in two sentences."""

    # YOUR CODE HERE

s1 = "I love bananas"

s2 = "I love to eat bananas"

s3 = "Nobody truly dislikes to eat bananas"

s4 = "I love to eat anything but bananas"

s5 = "I like mangos more than bananas"

check_equal(common_word_pairs(s1, s2), {("I", "love")})

check_equal(common_word_pairs(s2, s3), {("to", "eat"), ("eat", "bananas")})

check_equal(common_word_pairs(s3, s4), {("to", "eat")})

check_equal(common_word_pairs(s1, s5), set())

Solutions

Expert Solution

Solution:

The functions are written in python 3

Code for word_pairs()

def word_pairs(sentence):
    words=sentence.split()
    wordpairs=[]
    for i in range(0,len(words)-1):
        x=[]
        x.append(words[i])
        x.append(words[i+1])
        y=tuple(x)
        wordpairs.append(y)
    return wordpairs

Code for common_word_pairs()

def common_word_pairs(sentence1, sentence2):
    """Returns the set of common consecutive word pairs in two sentences."""
    # YOUR CODE HERE
    word_pairs1=word_pairs(sentence1)
    word_pairs2=word_pairs(sentence2)
    common = set([value for value in word_pairs1 if value in word_pairs2])
    return common 

Complete code:

def check_equal(x, y, msg=None):
    if x == y:
        if msg is None:
            print("Success")
        else:
            print(msg, ": Success")
    else:
        if msg is None:
            print("Error:")
        else:
            print("Error in", msg, ":")
        print("    Your answer was:", x)
        print("    Correct answer: ", y)
    assert x == y, "%r and %r are different" % (x, y)


def word_pairs(sentence):
    words=sentence.split()
    wordpairs=[]
    for i in range(0,len(words)-1):
        x=[]
        x.append(words[i])
        x.append(words[i+1])
        y=tuple(x)
        wordpairs.append(y)
    return wordpairs

check_equal(word_pairs(" "), [])
check_equal(word_pairs("woohoo"), [])
check_equal(word_pairs("I am"), [("I", "am")])

def common_word_pairs(sentence1, sentence2):
    """Returns the set of common consecutive word pairs in two sentences."""
    # YOUR CODE HERE
    word_pairs1=word_pairs(sentence1)
    word_pairs2=word_pairs(sentence2)
    common = set([value for value in word_pairs1 if value in word_pairs2])
    return common 

  
    
s1 = "I love bananas"
s2 = "I love to eat bananas"
s3 = "Nobody truly dislikes to eat bananas"
s4 = "I love to eat anything but bananas"
s5 = "I like mangos more than bananas"

check_equal(common_word_pairs(s1, s2), {("I", "love")})
check_equal(common_word_pairs(s2, s3), {("to", "eat"), ("eat", "bananas")})
check_equal(common_word_pairs(s3, s4), {("to", "eat")})
check_equal(common_word_pairs(s1, s5), set())

Screenshot of output:


Related Solutions

Let (X, dX) and (Y, dY) be metric spaces.Define the function d : (X × Y...
Let (X, dX) and (Y, dY) be metric spaces.Define the function d : (X × Y ) × (X × Y ) → R by d ((x1, y1), (x2,y2)) = dx(x1,x2)+dy(y1,y2) Prove that d is a metric on X × Y .
Let f(x,y) be a scalar function, and let F(x,y,z) be a vector field. Only one of...
Let f(x,y) be a scalar function, and let F(x,y,z) be a vector field. Only one of the following expressions is meaningful. Which one? a) grad f x div F b) div(curl(grad f)) c) div(div F) d) curl(div(grad f)) e) grad(curl F)
Let F (x, y) = y sin x i – cos x j, where C is...
Let F (x, y) = y sin x i – cos x j, where C is the line segment from (π/2,0) to (π, 1). Then C F•dr is A 1 B 2 C 5/2 D 3 E 7/2
Let X, Y ⊂ Z and x, y ∈ Z Let A = (X\{x}) ∪ {x}....
Let X, Y ⊂ Z and x, y ∈ Z Let A = (X\{x}) ∪ {x}. a) Prove or disprove: A ⊆ X b) Prove or disprove: X ⊆ A c) Prove or disprove: P(X ∪ Y ) ⊆ P(X) ∪ P(Y ) ∪ P(X ∩ Y ) d) Prove or disprove: P(X) ∪ P(Y ) ∪ P(X ∩ Y ) ⊆ P(X ∪ Y )
Don't use the p value method instead use the "5 steps of hypothesis testing." Or I...
Don't use the p value method instead use the "5 steps of hypothesis testing." Or I will get all of these wrong and I really need the help!! 9) An agent claims there is no difference between the pay of safeties and linebackers in the NFL. A survey of 15 randomly selected safeties found an average salary of $510,580. The standard deviation for the sample was $18,000. A survey of 15 randomly selected linebackers found an average salary of $527,360...
3. Let F : X → Y and G: Y → Z be functions. i. If...
3. Let F : X → Y and G: Y → Z be functions. i. If G ◦ F is injective, then F is injective. ii. If G ◦ F is surjective, then G is surjective. iii. If G ◦ F is constant, then F is constant or G is constant. iv. If F is constant or G is constant, then G ◦ F is constant.
. Let X and Y be a random variables with the joint probability density function fX,Y...
. Let X and Y be a random variables with the joint probability density function fX,Y (x, y) = { 1, 0 < x, y < 1 0, otherwise } . a. Let W = max(X, Y ) Compute the probability density function of W. b. Let U = min(X, Y ) Compute the probability density function of U. c. Compute the probability density function of X + Y ..
Let (X, Y) be a random vector with a function of the joint density given by...
Let (X, Y) be a random vector with a function of the joint density given by ˜ fX, Y (x, y) = k (2x + y) I (2,6) (x) I (0.5) (y) a) Determine k so that f X, Y (x, y) is a true probability density function joint quality. b) Determine the marginal probability density functions of X and Y. c) Calculate P (3 <X <4, Y> 2). d) Calculate P (X + Y> 4).
Let (X, Y) be a random vector with a function of the joint density given by...
Let (X, Y) be a random vector with a function of the joint density given by ˜ fX, Y (x, y) = k (2x + y) I (2,6) (x) I (0.5) (y) a) Determine k so that f X, Y (x, y) is a true probability density function joint quality. b) Determine the marginal probability density functions of X and Y. c) Calculate P (3 <X <4, Y> 2). d) Calculate P (X + Y> 4).
Example 3.5: Again let X = Y = R. Define g by g(x) = x2. The...
Example 3.5: Again let X = Y = R. Define g by g(x) = x2. The graph of this function has the familiar parabolic shape as in Figure 3.1(b). Then for example, g([0, 1]) = [0, 1], g([1, 2]) = [1, 4], g({−1, 1}) = {1}, g−1([0, 1]) = [−1, 1], g−1([1, 2]) = [− √ 2, −1]∪[1, √ 2], g−1([0, ∞)) = R. *I need help understanding why each example in bold is the answer it is* *Please explain...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT