首页 > 代码库 > Common Words
Common Words
Common Words
Let‘s continue examining words. You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
Tips: You can easily solve this task with several useful functions:str.split, str.join and sorted. Also try using the built-in type -- set.
Input: Two arguments as strings.
Output: The common words as a string.
题目大义:给出两个字符串,找出在两个字符串中同时出现的单词,并按字典序输出
当然使用了str.split方法,然后想到set有in方法,于是乎得到这么一段代码
1 def checkio(first, second): 2 first_str = first.split(‘,‘) 3 words_set = set(first_str) 4 5 second_str = second.split(‘,‘) 6 7 result = [] 8 9 for each in second_str:10 if each in words_set:11 result.append(each)12 else:13 words_set.add(each)14 15 result.sort()16 17 18 return ‘,‘.join(result);
接下来看了别人的解答,发现其实可以把两个字符串split后,转化为set,再使用set的intersection方法即可得到相同单词
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。