
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Word Break in Python
Suppose we have one non-empty string s and a dictionary wordDict. That is containing a list of non-empty words, determine when s can be segmented into a space-separated sequence of one or more dictionary words. We have to follow some rules −
- The same word in the dictionary may be reused multiple numbers of times in the segmentation.
- We can assume that the dictionary does not contain duplicate words.
Suppose the string s = “applepenapple”, and word dictionary is like [“apple”, “pen”], then the output will be true because the string s can be segmented as “apple pen apple”.
Let us see the steps −
- Define one matrix DP of order n x n. n = size of the string, and initialize it with false
- for i in range 1 to length of s
- for j in range 0 to length of s – i
- if substring s[j to j + 1] in dictionary, then dp[j, j+i - 1] := True
- otherwise
- for k in range j + 1 to j + i
- if dp[j, k - 1] and dp[k, j + i – 1], then dp[j, j + i – 1] := True
- for k in range j + 1 to j + i
- for j in range 0 to length of s – i
- return DP[0, length of s - 1]
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def wordBreak(self, s, wordDict): dp = [[False for i in range(len(s))] for x in range(len(s))] for i in range(1,len(s)+1): for j in range(len(s)-i+1): #print(s[j:j+i]) if s[j:j+i] in wordDict: dp[j][j+i-1] = True else: for k in range(j+1,j+i): if dp[j][k-1] and dp[k][j+i-1]: dp[j][j+i-1]= True return dp[0][len(s) - 1] ob1 = Solution() print(ob1.wordBreak("applepenapple", ["apple", "pen"]))
Input
"applepenapple" ["apple", "pen"]
Output
true
- Related Articles
- Word Break II in Python
- Word Break Problem
- CSS word-break property
- Minimum Word Break Problem in C++
- Break the line based on word with CSS
- How to indicate a potential word break point within a section in HTML?
- Word Search in Python
- Shortest Completing Word in Python
- Word Search II in Python
- How to break a for loop in Python?
- Longest Word in Dictionary in Python
- Python – Word Frequency in a String
- Break a list into chunks of size N in Python
- Loops and Control Statements (continue, break and pass) in Python
- Can we use break statement in a Python if clause?

Advertisements