this function will return True if all words in worddict is present in string . Word break problem

Viewed 61
def word_break(s,worddict):
    dp =[False] * (len(s) +1)
    dp[0] = True
    f = len(s)
    for i in range(len(s)):
        for word in worddict:
            k = len(worddict)
            if (len(word))<= len(s) and s[i:i+len(word)] == word:
               t = f-k
               dp[t] = True
               k-=1

    return dp[len(s)]

word_dict =['leet','code']
s = 'codeleet'
brk = word_break(s,word_dict)
print(brk)

I calculated the value of k to place true in such a way that I got answer at the last element of dp array.

My logic is not working as expected.

I am trying to put result in dp array after processing a word in such a way the last word result get placed on the last element of dp.

1 Answers

I'm not sure is that's what you expected but if you want to place True at the last element of the list you just need to delete your operation

t = f - k

because f is the len of the table and k is equal 2 so you place your True at the position dp[-3] for the last element True you need to do :

dp[f] = True
Related