Skip to content

Instantly share code, notes, and snippets.

@folksilva
Created January 23, 2018 20:02
Show Gist options
  • Save folksilva/dd8ff13c3e1d5c7c117cf9ee18859dcc to your computer and use it in GitHub Desktop.
Save folksilva/dd8ff13c3e1d5c7c117cf9ee18859dcc to your computer and use it in GitHub Desktop.
Daily Coding Problem: Problem #22
"""
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null.
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
https://dailycodingproblem.com/
"""
import itertools
import unittest
def problem22(dictionary, word):
all_combinations = []
sentences = []
for i in range(2, len(dictionary)+1):
all_combinations += itertools.permutations(dictionary, i)
for c in all_combinations:
if ''.join(c) == word:
sentences.append(list(c))
return sentences
class TestProblem22(unittest.TestCase):
def test_a(self):
dictionary = ['quick', 'brown', 'the', 'fox']
word = 'thequickbrownfox'
result = [['the','quick','brown','fox']]
self.assertItemsEqual(problem22(dictionary, word), result)
def test_b(self):
dictionary = ['bed','bath','bedbath','and','beyond']
word = 'bedbathandbeyond'
result = [['bed','bath','and','beyond'],['bedbath','and','beyond']]
self.assertItemsEqual(problem22(dictionary, word), result)
@johngaitho05
Copy link

Hey, I tested your solution with the following input and it doesn't work

dictionary = {"bedbathandbeyond", "and", "bath"}
word = "bedbathandbeyond"

@ErickMwazonga
Copy link

def reconstruction(words, s):
    words = set(words)
    res = []

    n = len(s)
    i = j = 0

    while j < n:
        if s[i:j+1] in words:
            res.append(s[i:j+1])
            i = j + 1
        else:
            if j == n - 1:
                return None
        
        j += 1
    
    return res

dictionary = ['bed', 'bath', 'bedbath', 'and', 'beyond']
word = 'bedbathandbeyond'
result = [['bed', 'bath', 'and', 'beyond'], ['bedbath', 'and', 'beyond']]
assert reconstruction(dictionary, word) in result

dictionary = ['quick', 'brown', 'the', 'fox']
word = 'thequickbrownfox'
result = [['the','quick','brown','fox']]
assert reconstruction(dictionary, word) in result

dictionary = ['quick', 'the', 'fox']
word = 'thequickbrownfox'
assert reconstruction(dictionary, word) is None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment