2
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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
athar
  • 31
  • 4
  • It's absolutely not obvious what you want to do here? `t = f-k` is always the same (given `s` and `worddict`), so - wild guess - do you actually want `k = len(word)`? – Timus Mar 30 '22 at 18:23
  • Run through your code with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to try to understand how your code works so that you can modify it to suit your requirements. – Alias Cartellano Mar 30 '22 at 22:36
  • yes , i reduce the value of k by 1 after a word is processed , k-=1 . so in this case k is not always remain the same . lets assume we have 2 words in worddcit if one word matches then t = 8-2 = 6 , so dp[6] = True , k-=1 , now k = 1 , if second word matches then t = 8-1 = 7 , so dp[7] = True (this is the last position) and im expecting getting answer at last position – athar Mar 31 '22 at 06:41
  • No, you don't: You set `for word in worddict: k = len(worddict)` in _each_ loop! `k -= 1` doesn't matter. – Timus Mar 31 '22 at 12:06

1 Answers1

1

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
Kal-1
  • 177
  • 1
  • 9