1

so I have a problem that I think it works as expected, but when I run the check50 it gives me all :)'s and just 1 error:

:( handles duplicate substrings in common Expected 4 matches, not 5

I checked further to see what the problem was, and it said that it's for inputs'foobarbaz' and 'barbaz', but when I tried printing it with those inputs (and I put n = 3, since that's the only way to expect 4 matches) and it worked fine again, returning ['bar', 'arb', 'rba', 'baz'].

What am I doing wrong?

from nltk.tokenize import sent_tokenize

def lines(a, b):
    """Return lines in both a and b"""
    result = []
    for line in a.split("\n"): #a je lista koja sadrzi redove bez \n
        if line in b.split("\n"):
            if line != "":
                result.append(line)

    return result


def sentences(a, b):
    """Return sentences in both a and b"""
    result = []
    a = sent_tokenize(a, language='english')
    b = sent_tokenize(b, language='english')
    for line in a:
        if line in b:
            if line != "" and line.strip() not in result:
                result.append(line.strip())
    return result


def substrings(a, b, n):
    """Return substrings of length n in both a and b"""

    #this works only if a and b are just 1 word
    a = a.split(" ")
    result = []
    #splits 1 text into a list whose elements are single words
    for word in a:
        listofsubs = find_substrings(word.strip(":;,."), n)
        for sub in listofsubs:
            if b.find(sub) != -1:
                result.append(sub)

    return result

def find_substrings(a, n):
    """Return list of substrings of length n"""
    result = []
    i = 0
    while (i + n) < len(a) + 1:
        result.append(a[i:i+n])
        i += 1
    return result
2

You likely reported a result twice, consider foobarbaz, barbaz, and n=2. You are to return the unique lines/sentences/substrings common to both strings, in any order, which is ["ba", "ar", "rb", "az"] ("ba" appears twice, but is reported once).

I used the set datatype for that part, it's like an unordered list that can hold anything only once, and it supports intersections natively.

An alternative would be to check whether that particular substring is in result before appending, which would be a minimal change to your current code.

1
  • Thanks, for some reason I thought I was already checking if the substrings were in result.. I also managed to make it work with sets too. Appreciate your help :) – F.Ljubic Feb 9 '19 at 10:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .