码迷,mamicode.com
首页 > 其他好文 > 详细

Common Words

时间:2014-08-05 10:54:19      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:blog   http   使用   io   strong   for   ar   cti   

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

Common Words,布布扣,bubuko.com

Common Words

标签:blog   http   使用   io   strong   for   ar   cti   

原文地址:http://www.cnblogs.com/hzhesi/p/3891489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!