word_break

 1from functools import cache
 2
 3
 4# @leet start
 5class Solution:
 6    def wordBreak(self, s: str, wordDict: list[str]) -> bool:
 7        """
 8        This question asks us to see if we can use the words in `wordDict` as
 9        many times as we want to reconstruct the string `s`.
10
11        To do this, we can dfs through the given word choices and cache
12        our decisions, so if we get to the same choice more than once we
13        don't have to redo the same computation.
14        """
15
16        @cache
17        def dfs(s):
18            if not s:
19                return True
20            return any(
21                dfs(s[len(word) :]) if s.startswith(word) else False
22                for word in wordDict
23            )
24
25        return dfs(s)
26
27
28# @leet end
29
30
31def test():
32    assert 2 + 2 == 4
class Solution:
 6class Solution:
 7    def wordBreak(self, s: str, wordDict: list[str]) -> bool:
 8        """
 9        This question asks us to see if we can use the words in `wordDict` as
10        many times as we want to reconstruct the string `s`.
11
12        To do this, we can dfs through the given word choices and cache
13        our decisions, so if we get to the same choice more than once we
14        don't have to redo the same computation.
15        """
16
17        @cache
18        def dfs(s):
19            if not s:
20                return True
21            return any(
22                dfs(s[len(word) :]) if s.startswith(word) else False
23                for word in wordDict
24            )
25
26        return dfs(s)
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
 7    def wordBreak(self, s: str, wordDict: list[str]) -> bool:
 8        """
 9        This question asks us to see if we can use the words in `wordDict` as
10        many times as we want to reconstruct the string `s`.
11
12        To do this, we can dfs through the given word choices and cache
13        our decisions, so if we get to the same choice more than once we
14        don't have to redo the same computation.
15        """
16
17        @cache
18        def dfs(s):
19            if not s:
20                return True
21            return any(
22                dfs(s[len(word) :]) if s.startswith(word) else False
23                for word in wordDict
24            )
25
26        return dfs(s)

This question asks us to see if we can use the words in wordDict as many times as we want to reconstruct the string s.

To do this, we can dfs through the given word choices and cache our decisions, so if we get to the same choice more than once we don't have to redo the same computation.

def test():
32def test():
33    assert 2 + 2 == 4