def is_in_dict(word, dictionary):
return word in dictionary
def word_break(s, result, dictionary):
for i in range(1, len(s) + 1):
sub_str = s[:i]
if is_in_dict(sub_str, dictionary):
if i == len(s):
print(result + sub_str)
return
word_break(s[i:], result + sub_str + " ", dictionary)
s = "butterflyplaybasketballwithbags"
dictionary = {
"butterfly", "basketball", "bagpiper", "and", "play",
"with", "butter", "fly", "basket", "ball", "bags"
}
word_break(s, "", dictionary)
'''
run:
butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags
'''