pythonalgorithmword-break

maximum word split


Given a string s and a dictionary of valid words d, determine the largest number of valid words the string can be split up into.

I tried solving this problem with the code below but it is not giving me the answer I am looking for.

def word_split_dp(s):
    n = len(s)
    ans = [0]*n
    # base case
    ans[0] = 0
    for i in range(1, len(s)):
        ans[i] = float('-inf')
        for j in range(1, i-1):
            ans[i]= max(ans[i], ans[i-j] + wordcheck(s,i,j))
   
    print(ans)
    return ans[n-2]
       
        
       
        
       
        
def wordcheck(s,i,j):
    
    for word in dict:
        start = i-j+1
        if(s[start:i] == word):
            return 1
        else:
            return float('-inf')
        

print(word_split_dp(s))

Solution

  • There are a few issues in your attempt. Starting from the top:

    Those are the issues. The code with all those corrections:

    def word_split_dp(s):
        n = len(s)
        ans = [0]*(n+1)  #correction
        # base case
        ans[0] = 0
        for i in range(1, len(s) + 1): # correction
            ans[i] = float('-inf')
            for j in range(1, i + 1): # correction
                ans[i] = max(ans[i], ans[i-j] + wordcheck(s,i,j))
       
        print(ans)
        return ans[n] # correction
            
    def wordcheck(s,i,j):
        words=("war","month","on","the","heat","eat","he","arm","at")
        for word in words:
            start = i-j # correction
            if s[start:i] == word:
                return 1
            # don't interrupt loop otherwise
        return float('-inf')
            
    s="warmontheheat"
    print(word_split_dp(s))  # -inf
    s="warontheheat"
    print(word_split_dp(s))  # 5