简体   繁体   中英

maximum word split using Recursion

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 using Recursion

I tried solving this problem with the code below but it is not giving me the answer I am looking for. Can someone please help me understand how Recursion can be used to solve this problem. I am particularly trying to get the maximum number of words. for example- "warmontheat" can be divided into maximum 4 words- warm on the at.

def wordBreak( s, wordDict):
    
        if len(s)==0:
            return 0
        for end in range( 1, len(s) + 1):
            if s[0:end] in wordDict and wordBreak(s, wordDict):
                return 1
       
 
        return wordBreak(s, wordDict)

s="warmontheat"
words=("war","month","on","the","heat","eat","he","arm","at","warm")
print(wordBreak(s,words))

There are these issues:

  • The recursive call is made with the same values for both arguments, which means the recursion -- if it starts -- will never end: the conditions are always the same. The aim of recursion is to solve a smaller problem, so you should pass a shorter string -- without the prefix that was just matched. So pass s[end:] .

  • The recursive call is made as if it returns a boolean, but you'll want to know how many partitions were made, so making that call in an if condition is not going to help with that. You need to make that call inside the if block and do something with the result you got from it.

  • With return 1 you're actually saying the recursive call only managed to chop the string up into one partition, but this is not true. Another way to put it: your function is only able to return 0 or 1, nothing else. Instead, the returned value should depend on the number you get back from recursion.

  • It is wrong to have a return inside the loop. There might be cases where you have success with a word, but actually need an alternative, longer word first in order to benefit from shorter words in the rest of the string, and so you cannot assume that the first success corresponds to the optimal solution. The loop must continue to make iterations, and only when the loop has completed, you can know which of the valid options is the optimal one.

Here is the corrected code:

def wordBreak(s, wordDict):
    if len(s) == 0:
        return 0
    result = float('-inf')
    for end in range(1, len(s) + 1):
        if s[:end] in wordDict:
            result = max(result, wordBreak(s[end:], wordDict))
    return 1 + result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM