-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCS375_Lab7.py
49 lines (41 loc) · 1.39 KB
/
CS375_Lab7.py
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
# Input: string s and list of strings m
# Output: Possible setntence combinations
def spaceBar(s, m):
memo = {}
# Convert m into a set
wordDict = set(m)
# Helper function for subproblem
def helper(s, wordDict):
if s not in memo:
result = []
# Traverse through all the element of the dictionary
for word in wordDict:
# check if prefix exists in the dictionary
if s[:len(word)] == word:
# Base Case
if len(s) == len(word):
result.append(word)
else:
# Recursively call helper to find other words later in the string
for w in helper(s[len(word):], wordDict):
result.append(word+" "+w)
memo[s] = result
return memo[s]
return helper(s, wordDict)
def main():
s1 = "amantentononewitheel"
m1 = ["a", "an", "am", "ant", "ent", "tent", "man", "ten", "on", "one",
"ton", "no", "none", "new", "with", "pass", "the", "he", "heel", "wit"]
if len(spaceBar(s1, m1)) > 0:
print("Yes")
else:
print("No")
print(spaceBar(s1, m1))
s2 = "amango"
m2 = ["a", "am", "an", "man", "go"]
if len(spaceBar(s2, m2)) > 0:
print("Yes")
else:
print("No")
print(spaceBar(s2, m2))
main()