写了一个作业,比较两个单词,看前一个单词能否用后一个单词中的字母拼接出来。 Your task will be to write a function can_be_composed(word1, word2) to check if word1 can be composed from word2 . Put your function into a file compose.py. Example usages: • can_be_composed("python", "pantyhose") returns True • can_be_composed("python", "ponytail") returns False • can_be_composed("code", "docent") returns True • can_be_composed("messy", "reassembly") returns True • can_be_composed("computational", "alphanumeric") returns False • can_be_composed("linguistics", "criminologists") returns False
思路是先把单词转换成 dict,然后再比较, import collections def word2dict(word):
word2dict=dict(collections.Counter(word))
return word2dict
def can_be_composed(word1,word2): dw1=word2dict(word1) dw2=word2dict(word2)
for key in dw1.keys():
if key in list(dw2.keys()) and dw1[key] <= dw2[key]:
return True
else:
return False
但是我每次得出的都是 True,后来发现, for key in dw1.keys(): if key in list(dw2.keys()) and dw1[key] <= dw2[key]: return True
这得出的结果是每个 key 的值的比较,输出的是一系列的对比结果,
问题来了,对于 if key in list(dw2.keys()) and dw1[key] <= dw2[key]:,如何能够在对比只要得出 false 就输出 false,只有全部都是 True 才输出 true ?
或者有没有更简单的方法?
附上原题, Exercise 3. We will say that a word “can be composed” from another word if it is possible to select some of the letters from the second word (maybe all of them) to build the first one (possibly changing the order). For example, word “python” can be composed from words “pantyhose”, “immunotherapy”, or “hypnotists”. It can not be composed from word “ponytail” because “ponytail” does not have a letter “h”. Similarly, word “lesson” can be composed from “professional” or “responsible”, but it can not be composed from word “longest” as “longest” does not have enough “s” letters. Your task will be to write a function can_be_composed(word1, word2) to check if word1 can be composed from word2 . Put your function into a file compose.py. Example usages: • can_be_composed("python", "pantyhose") returns True • can_be_composed("python", "ponytail") returns False • can_be_composed("code", "docent") returns True • can_be_composed("messy", "reassembly") returns True • can_be_composed("computational", "alphanumeric") returns False • can_be_composed("linguistics", "criminologists") returns False Hint: Write a function word2dict(word) which will convert word to a dictionary with an information how many times every letter occured in word . Use word2dict in your can_be_composed function.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.