-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-can_construct.py
More file actions
54 lines (41 loc) · 1.85 KB
/
Copy path6-can_construct.py
File metadata and controls
54 lines (41 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import functools
print("******* Recursive and Memoization *******")
def list_to_tuple(function):
def wrapper(*args):
args = [tuple(x) if type(x) == list else x for x in args]
result = function(*args)
result = tuple(result) if type(result) == list else result
return result
return wrapper
@list_to_tuple
@functools.lru_cache(maxsize=None)
def can_construct (target, word_bank):
if target == "": return True
for word in word_bank :
if target.startswith(word):
suffix = target[len(word):]
if can_construct(suffix, word_bank) == True:
return True
return False
print(can_construct("abcdef", ["ab","abc","cd","def","abcd"])) # true
print(can_construct("skateboard", ["bo","rd","ate","t","ska","sk","boar"])) # false
print(can_construct("enterapotentpot", ["a","p","ent","enter","ot","o","t"])) # true
print(can_construct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",[
"e","eeee","eeeeeee","eeeeeeeeee","ee","eee","eeeee" # false
]))
print("******* Tabulation *******")
def can_construct2(target, word_bank):
table = [False for i in range((len(target)+1))]
table[0] = True
for i in range(len(target)):
if table[i]:
for word in word_bank:
if target[i:i+len(word)] == word:
table[i+len(word)] = True
return table[len(target)]
print(can_construct2("abcdef", ["ab","abc","cd","def","abcd"])) # true
print(can_construct2("skateboard", ["bo","rd","ate","t","ska","sk","boar"])) # false
print(can_construct2("enterapotentpot", ["a","p","ent","enter","ot","o","t"])) # true
print(can_construct2("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",[
"e","eeee","eeeeeee","eeeeeeeeee","ee","eee","eeeee" # false
]))