1. 程式人生 > >入坑codewars第五天-Dubstep、Regex validate PIN code

入坑codewars第五天-Dubstep、Regex validate PIN code

第一題:

題目:

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.

Let's assume that a song consists of some number of words. 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.

For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".

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.

input:

Input
The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters

output:

Output
Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.
Examples
song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
  # =>  WE ARE THE CHAMPIONS MY FRIEND

題目意思就是:將所有的WUB替換成空格,然後將頭尾的空格去掉

此時可以用正則表示式:

r'WUB+'就代表至少一個或者多個WUB

利用正則表示式的re.sub()函式

再利用strip()函式去掉字串頭尾的空格“ ”

程式碼如下:

import re
def song_decoder(song):
    song = re.sub(r'(WUB)+'," ",song)#利用正則表示式把WUB替換成空格,"(WUB)+"表示至少一個WUB或者多個WUB
    song = song.strip(" ")#替換掉開頭結尾的“ ”
    return song

補充:

排名第一的最簡單的程式碼:

相當厲害,思路:字串列表互相轉換

(1)將字串中的WUB都替換成空格

(2).split()就是將分割後的字串變成列表

(3).join()再把列表轉成字串,以空格相連


總結

1.正則表示式
本題想考察的應該是正則表示式,找出字串中要替換字元的規律,用正則表示式進行操作。關鍵是要字元的規律是什麼?正則表示式可以應用在非常多的場合,判斷是不是中國的手機號,判斷是不是郵箱等等。用數字、字母和符號就能向計算機將規律表達出來。

2.字串和列表的相互轉換
str ————> list 用split()
list ————> str 用 ‘ ’.join
多多應用,熟練物件的互相轉換。

 

 

第二題:

                   

題目意思就是:只能四個數或者六個數,且不能有非數字

我的思路就是:

(1)先統計數字個數

(2)如果數字個數是4且字串長度是4;或者數字個數是6且字串長度是6;這兩種情況返回True,其他情況返回False

def validate_pin(pin):
    digits=0
    for c in pin:
        if c.isdigit():
            digits=digits+1
            print(digits)
    if digits==4 and len(pin)==4:
        return True
    elif digits==6 and len(pin)==6:
        return True
    else:
        return False

這裡運用了python的函式:

輸入一行字元,分別統計出其中英文字母、空格、數字和其它字元的個數。

方法isalpha()判斷是否英文字母;

方法isspace()判斷是否空格;

方法isdigit()判斷是否為數字。

還是很方便的。

但是下面我參考一下其他人寫的精簡程式碼:

查了一下:isdigit()就能判斷字串是否是數字,因此思路就是可以直接判斷長度是否是是4或6,且是否都是數字