The end of other (Library 2.0) - 接尾語のチェック
どんな問題?
The end of other
http://www.checkio.org/mission/end-of-other/
英小文字の単語セットの中から、他の単語の接尾語(suffix)になっている単語があるかどうか調べよ。
アイコンがかわいい。
例題:
checkio({"hello", "lo", "he"}) == True checkio({"hello", "la", "hellow", "cow"}) == False checkio({"walk", "duckwalk"}) == True checkio({"one"}) == False checkio({"helicopter", "li", "he"}) == False
どうやって解く?
接尾語かどうかは、str.endswith()メソッドを使えばいい。
ワードをすべて組み合わせてチェックすればいいわけだが、これはitertoolsを使えばいいかな。
itertools.permutations()で重複なしの順列が得られる。(A,B,Cなら AB,AC,BA,BC,CA,CBの6つ)
import itertools def checkio(words_set): return any(a.endswith(b) for a, b in itertools.permutations(words_set, r=2))
itertoolsを使わずに、こう書いても同じ。
def checkio(words_set): return any(a != b and a.endswith(b) for a in words_set for b in words_set)
他の人の答え
str.endswith()って、タプルで複数の値を一度にチェックできるんだ。知らなかった。
if word.endswith(tuple((w for w in words_set if w != word))):
http://www.checkio.org/mission/end-of-other/publications/rfonseca/python-3/worst-fixed/
じゃあ、こういう書き方もできるんだ。
def checkio(words_set): return any(a.endswith(tuple(words_set - {a})) for a in words_set)