Skip to content

Commit 3815a97

Browse files
authored
Add all_construct dynamic programming implementation (#5626)
* Add all_construct dynamic programming implementation * all_construct: remove the main function * all_construct: Add type hints * all_construct: changed map to list comprehension,fix mutable default arguments * all_construct: fixed type hints * all_construct: cleaner code for initializing word_bank argument * all_construct: added an import for annotations * all_construct: added None in the argument with word_bank * all_construct: fixed a type hint * all_construct: Fixed some more type hints
1 parent 47dd31f commit 3815a97

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

dynamic_programming/all_construct.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Program to list all the ways a target string can be
3+
constructed from the given list of substrings
4+
"""
5+
from __future__ import annotations
6+
7+
8+
def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]:
9+
"""
10+
returns the list containing all the possible
11+
combinations a string(target) can be constructed from
12+
the given list of substrings(word_bank)
13+
>>> all_construct("hello", ["he", "l", "o"])
14+
[['he', 'l', 'l', 'o']]
15+
>>> all_construct("purple",["purp","p","ur","le","purpl"])
16+
[['purp', 'le'], ['p', 'ur', 'p', 'le']]
17+
"""
18+
19+
word_bank = word_bank or []
20+
# create a table
21+
table_size: int = len(target) + 1
22+
23+
table: list[list[list[str]]] = []
24+
for i in range(table_size):
25+
table.append([])
26+
# seed value
27+
table[0] = [[]] # because empty string has empty combination
28+
29+
# iterate through the indices
30+
for i in range(table_size):
31+
# condition
32+
if table[i] != []:
33+
for word in word_bank:
34+
# slice condition
35+
if target[i : i + len(word)] == word:
36+
new_combinations: list[list[str]] = [
37+
[word] + way for way in table[i]
38+
]
39+
# adds the word to every combination the current position holds
40+
# now,push that combination to the table[i+len(word)]
41+
table[i + len(word)] += new_combinations
42+
43+
# combinations are in reverse order so reverse for better output
44+
for combination in table[len(target)]:
45+
combination.reverse()
46+
47+
return table[len(target)]
48+
49+
50+
if __name__ == "__main__":
51+
print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"]))
52+
print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"]))
53+
print(
54+
all_construct(
55+
"hexagonosaurus",
56+
["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"],
57+
)
58+
)

0 commit comments

Comments
 (0)