先頭文字の大文字化(capitalize)を使う例題[7/13/2012] Challenge #76 [easy] (Title case) : dailyprogrammer

redditのdailyprogrammerが楽しげです。

問題

Challenge #76 (Title case) : dailyprogrammer
文字列のそれぞれの単語の先頭文字を大文字にする(capitalize)関数を作る。ただしexceptionsで渡された単語は除いて。なおexceptionsに含まれるものであっても文字列の先頭単語は大文字にする。

exceptions = ['jumps', 'the', 'over']
titlecase('the quick brown fox jumps over the lazy dog', exceptions)

# This should return:
# The Quick Brown Fox jumps over the Lazy Dog

exceptions = ['are', 'is', 'in', 'your', 'my']
titlecase('THE vitamins ARE IN my fresh CALIFORNIA raisins', exceptions)

# Returns:
# The Vitamins are in my Fresh California Raisins

回答

def titlecase(string, exceptions):
    xs = string.split(" ")
    results = []
    def capitalize_if(string, exceptions):
        if string in exceptions:
            return string
        else:
            return string.capitalize()
    for x in xs:
        x = capitalize_if(x.lower(), exceptions)
        results.append(x)
    results[0] = results[0].capitalize()
    return " ".join(results)

exceptions = ['jumps', 'the', 'over']
print titlecase('the quick brown fox jumps over the lazy dog', exceptions)
exceptions = ['are', 'is', 'in', 'your', 'my']
print titlecase('THE vitamins ARE IN my fresh CALIFORNIA raisins', exceptions)

# Outputs:
# The Quick Brown Fox jumps over the Lazy Dog
# The Vitamins are in my Fresh California Raisins

リンク先のbenzinonapoloni氏と全く同じ方法だと気づいたがこちらのコードはこなれてないのがありありで悔しい。スライシングとリスト内包表記をもっと活用したいね。

AOJやProject Eulerよりもとっつきやすいと思うのでdailyprogrammerの紹介記事とか翻訳とか増えたらいいな。