CodeWars 10: Dubstep


問題の説明


Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
ポーリー・カバースはフランク・ナイトクラブで最高のDJだ.特にダブルステップの音楽が私の特技です最近、彼はいくつかの古い歌を自分のダブルチャネルの混音にすることにした.
Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB"before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
原曲はもちろんですが、たくさんの単語で構成されています(ここではWUBという言葉はないでしょう)ホットステップスタイルでミックスするため、ボリー・カバースは曲の真ん中に「WUB」という言葉を挿入することにしました.単語の間には1つ以上置かなければなりませんが、文の先頭と末尾は置かなくてもいいです.これらの再結合された歌詞は、WUBという言葉を組み合わせた長い文字列フォーマットが現れ、クラブ音楽になります.
For example, a song with words "I AM X"can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX"and cannot transform into "WUBWUBIAMWUBX".
例えば、「I AM X」の歌詞があれば、ダブルステップミックス風の歌詞は「WUBWUBIWUBAWUBX」になります.「WUBWUBIAMWUBX」は正しく再結合されていない.(単語の間にWUBが欠けている)
Recently, Jonny has heard Polycarpus's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.
最近、ジョニーはボリー・カバースの新しいダブルペダルコースを聞いた.実は、カバーした音楽よりも以前の原曲の方が好きなので、ボリー・カフスがカバーした前の歌詞が気になって、復元したいと思っています.はい、今一度手伝ってくれませんか.

せいげんじょうけん


入力
与えられた再結合された歌詞は大文字のみで200文字を超えない.単語のない歌詞はあげない
しゅつりょく
スペースを正しく適用した(1つのスペース)復元の歌詞を出力してください.
歌詞の先頭と末尾にスペースを入れてはいけません' I AM X '->歌詞が正しくありません.

I/O例

song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
  # =>  WE ARE THE CHAMPIONS MY FRIEND

に答える

import re
def song_decoder(song):
    return re.sub('\s+', ' ', song.replace("WUB", " ")).strip()
  • のスペースに焦点を当てて変換しました.まず「WUB」に対してスペース処理を行います.単語間の「WUB」の数はランダムなので、スペースの長さは千差万別です.
  • まずstrip()と書いて字の左右(先頭と末尾)のスペースを抜きます.
  • 正規表現を使用して、1つ以上のスペースを1つのスペースに強制的に置き換えます.
  • 別の解釈

    import re
    def song_decoder(song):
        return re.sub('(WUB)+', ' ', song).strip()
    方法はほぼ同じで、1つ以上のWUBを1つのスペースに変換してスクリプト処理を行っただけです.
    プロセスが1つ減った
    import re
    def song_decoder(song):
        return " ".join(song.replace('WUB', ' ').split())
    split()文字列は、スペースに基づいて要素化され、リストに含まれます." "(한칸공백)と接続すればいいです.