新农上路
- 积分
- 97
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-12-10
- 最后登录
- 1970-1-1
|
- from collections import Counter
- from collections import namedtuple
- # return True if word can be formed
- # false otherwise
- def dfs(tuples, d): # both are
- if len(d) == 0: # all letters found match
- return True
- if len(tuples) == 0: # no more avaliable tuples to choose
- return False
- for char, count in d.items():
- candidate_tuples = [t for t in tuples if char in t] # all the tuples contain this
- for t in candidate_tuples:
- d[char] -= 1
- if d[char] == 0:
- del d[char]
- tuples[t] -= 1
- if tuples[t] == 0:
- del tuples[t]
- if dfs(tuples, d):
- return True
- # backtracking
- d[char] = d.get(char, 0) + 1
- tuples[t] = tuples.get(t, 0) + 1
- return False
- def main(lst_of_tupules, target):
- # first, change the tuples into a dictionary, since only the count of each letter matters
- d = Counter(target) # "hello" => {"h": 1, "e": 1, "l": 2, "o":1}
- tuples = Counter(lst_of_tupules) # [("a", "b"), ("c", "d"), ("c", "d")] => {("a", "b"): 1, ("c", "d"): 2}
- return dfs(tuples, d)
- """Let the size of tuples be n, let the lenght of target word be n,
- Time: O(m ** n), Exponential
- Space: O(m + n), since we create two additional dictionary
- """
- if __name__ == '__main__':
- Test = namedtuple('Test', ['tuples_lst', 'target_word'])
- test1 = Test(tuples_lst = [("a", "b"), ("c", "d"), ("h", "e")], target_word="ade")
- assert(main(test1.tuples_lst, test1.target_word) == True)
- test2 = Test(tuples_lst = [("a", "b"), ("c", "d"), ("h", "e")], target_word="hello")
- assert(main(test2.tuples_lst, test2.target_word) == False)
- test3 = Test(tuples_lst = [("h", "e"), ("f", "e"), ("l", "e"), ("l", "e"), ("m", "n"), ("o", "h")], target_word="hello")
- assert(main(test3.tuples_lst, test3.target_word) == True)
- test4 = Test(tuples_lst = [("h", "e"), ("f", "e"), ("l", "e"), ("l", "e"), ("m", "n")], target_word="hello")
- assert(main(test4.tuples_lst, test4.target_word) == False)
- test5 = Test(tuples_lst = [("t", "e"), ("p", "u"), ("a", "b"), ("c", "d"), ("m", "n")], target_word="tupac")
- assert(main(test5.tuples_lst, test5.target_word) == False)
- test6 = Test(tuples_lst = [("t", "e"), ("p", "u"), ("a", "b"), ("c", "d"), ("u", "p")], target_word="tupac")
- assert(main(test6.tuples_lst, test6.target_word) == True)
- test7 = Test(tuples_lst = [("t", "e"), ("p", "u"), ("a", "b"), ("c", "d"), ("p", "u")], target_word="tupac")
- assert(main(test7.tuples_lst, test7.target_word) == True)
复制代码 |
|