Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 136990b

Browse files
Code refactored
1 parent ce18884 commit 136990b

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

‎DynamicProgramming/wordBreak.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,7 @@ def word_break(string: str, words: list[str]) -> bool:
5050
...
5151
ValueError: the words should be a list of non-empty strings
5252
"""
53-
54-
# Validation
53+
5554
if not isinstance(string, str) or len(string) == 0:
5655
raise ValueError("the string should be not empty string")
5756

@@ -60,22 +59,25 @@ def word_break(string: str, words: list[str]) -> bool:
6059
):
6160
raise ValueError("the words should be a list of non-empty strings")
6261

63-
64-
# Build trie
65-
trie: dict[str, Any] = {}
6662
word_keeper_key = "WORD_KEEPER"
6763

68-
for word in words:
69-
trie_node = trie
70-
for c in word:
71-
if c not in trie_node:
72-
trie_node[c] = {}
64+
# Helper function to build the trie
65+
def build_trie(words: list[str]) -> dict[str, Any]:
66+
trie: dict[str, Any] = {}
7367

74-
trie_node = trie_node[c]
68+
for word in words:
69+
trie_node = trie
70+
for c in word:
71+
if c not in trie_node:
72+
trie_node[c] = {}
73+
trie_node = trie_node[c]
74+
trie_node[word_keeper_key] = True
7575

76-
trie_node[word_keeper_key] =True
76+
returntrie
7777

78-
len_string = len(string)
78+
# Build trie
79+
trie = build_trie(words)
80+
strLength = len(string)
7981

8082
# Dynamic programming method
8183
@functools.cache
@@ -85,17 +87,17 @@ def is_breakable(index: int) -> bool:
8587
>>> is_breakable(1)
8688
True
8789
"""
88-
if index == len_string:
90+
if index == strLength:
8991
return True
9092

9193
trie_node = trie
92-
for i in range(index, len_string):
93-
trie_node = trie_node.get(string[i], None)
94+
for letter in range(index, strLength):
95+
trie_node = trie_node.get(string[letter], None)
9496

9597
if trie_node is None:
9698
return False
9799

98-
if trie_node.get(word_keeper_key, False) and is_breakable(i + 1):
100+
if trie_node.get(word_keeper_key, False) and is_breakable(letter + 1):
99101
return True
100102

101103
return False

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /