Common Words

时间:2023-03-08 17:46:42

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.splitstr.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方法即可得到相同单词