File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ def wordBreak(dict, str, out=""): # Recursion
2+ if len(str)==0:
3+ print(out)
4+ return
5+
6+ for i in range(1, len(str) + 1):
7+ prefix = str[:i]
8+
9+ if prefix in dict:
10+ wordBreak(dict, str[i:], out + " " + prefix)
11+
12+ def word_break_alternate(dict, str): # Alternate way of Recursion but to avoid repetition
13+ return True
14+
15+ for i in range(1, len(str) + 1):
16+ prefix = str[:i]
17+ if prefix in dict and wordBreak(dict, str[i:]):
18+ return True
19+ return False
20+
21+
22+ def wordbreak_dp(word,dict): # Dynamic programming
23+ m =len(word)
24+ T = [[False for x in range (m)] for y in range (m)]
25+
26+ for l in range(1,m+1):
27+ for i in range(0,m-l+1):
28+ j = i + l-1
29+ str = word[i:j+1]
30+ if str in dict:
31+ T[i][j] = True
32+ continue
33+
34+ for k in range(i+1,j+1):
35+ if (T[i][k - 1] != False and T[k][j] != False):
36+ T[i][j] = True
37+ break
38+
39+ if T[0][m-1] == False:
40+ return False
41+ else:
42+ return True
You can’t perform that action at this time.
0 commit comments