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

转载于:https://www.cnblogs.com/hzhesi/p/3891489.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值