summer_tree_home

Check iOでPython3をマスターするぜっ

The Common Words (Library 2.0) - 共通の単語を探せ

どんな問題?

The Common Words
http://www.checkio.org/mission/common-words/

2つの文字列に共通して出てくる単語を探せ。

引数は、コンマ区切りの文字列2つ。
戻り値は、コンマ区切りの文字列。単語はアルファベット順に並べること。
ヒント:str.split、str.join、sorted、set(集合型)を使おう。

例題:

checkio("hello,world", "hello,earth") == "hello"
checkio("one,two,three", "four,five,six") == ""
checkio("one,two,three", "four,five,one,two,six,three") == "one,three,two"

どうやって解く?

ヒントにほとんど答えが書いてあるが、

  1. str.split() を使ってコンマ区切り文字列を分解する
  2. set(集合型)で、共通の項目を取り出す
  3. str.join() で、コンマ区切り文字列を生成する

という流れだろう。

def checkio(first, second):
    words1 = set(str.split(first, ','))
    words2 = set(str.split(second, ','))
    common_words = words1 & words2
    return ','.join(sorted(common_words))

これまた簡単。

他の人の答え

http://www.checkio.org/mission/common-words/publications/bryukh/python-3/intersection/

words1 & words2

は、

words1.intersection(words2)

と書くこともできる。
intersection() の場合、引数はsetである必要はない。(iterableであればよい)
しかし、演算子の & を使う場合は、どちらもsetでなくてはならない。

>>> a = {1,2,3}  # set
>>> b = [3,4,5]  # list
>>> a.intersection(b)
{3}

>>> a & b
TypeError: unsupported operand type(s) for &: 'set' and 'list'

へー、知らなかった。