Python小白的日常練習之Codewars

Python小白的日常練習之Codewars

來自專欄 Python小白的日常練習

今天看微信公眾號「菜鳥學Python",安利了一個代碼練習網站Codewars。鏈接如下

Sign in | Codewars?

www.codewars.com圖標

感覺挺有用的,就去試了一下。完成了第一題。一道6級題(最低是8級,最高為1級)

題目: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.

Lets 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 Polycarpuss new dubstep track, but since he isnt into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.

Input

The input consists of a single non-empty string, consisting only of uppercase English letters, the strings length doesnt exceed 200 characters

Output

Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.

題目非常有意思,還會有一個故事背景。如果只留下技術性問題的話,如下:

輸入一個字元串,字元串都是大寫的英文字母,無空格,且不超過200個字元。字元串中包括若干「WUB」,需要把「WUB」用空格替換掉,並輸出。且首尾不存在空格。

如:"WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"

輸出結果為

WE ARE THE CHAMPIONS MY FRIEND

我的代碼如下:

def song_decoder(song): import re # 匹配1個及多個空格 pattern = re.compile(rs+) song_1 = re.search(pattern, song, flags=0) if (len(song)>200): return exceed 200 characters if (song_1 is None and song.isupper()):##如果字元串沒有空格且所以字元都是大寫 pattern_WUB = re.compile(r(WUB)+) new_song = re.sub(pattern_WUB, ,song) print(new_song) a = new_song.lstrip() b = a.rstrip() return b return "Incorrect format"

運用到了正則表達式。

(1)re.search(pattern, string, flags=0) 掃描整個字元串並返回第一個成功的匹配。否則返回None。flags是標誌位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。詳見

Python3 正則表達式 | 菜鳥教程?

www.runoob.com

(2)str.isupper()是判斷字元串中字母是否為大寫。類似的還有

s.isalnum() #所有字元都是數字或者字母

s.isalpha() #所有字元都是字母

s.isdigit() #所有字元都是數字

s.islower() #所有字元都是小寫

s.isupper() #所有字元都是大寫

s.istitle() #所有單詞都是首字母大寫,像標題

s.isspace() #所有字元都是空白字元、 、

## 轉換

s.upper() #把所有字元中的小寫字母轉換成大寫字母

s.lower() #把所有字元中的大寫字母轉換成小寫字母

s.capitalize() #把第一個字母轉化為大寫字母,其餘小寫

s.title() #把每個單詞的第一個字母轉化為大寫,其餘小寫

(3)re.sub(pattern, repl, string, count=0)用於替換字元串中的匹配項。

  • pattern : 正則中的模式字元串。
  • repl : 替換的字元串,也可為一個函數。
  • string : 要被查找替換的原始字元串。
  • count : 模式匹配後替換的最大次數,默認 0 表示替換所有的匹配。

這一步結束後,所有WUB的地方全都變成了空格。由於(WUB)+是匹配一次或多次,因此即使有WUB連續的部分也會只替換為一個空格。

(4)使用strip,lstrip,rstrip方法去前後空格

這三種方法默認就是去空格。調用方法是str.lstrip()——去前空格。str.lstrip()——去後空格

當然也可以去掉其他字元,只要在括弧中加入相應字元即可,如:str.strip (a) 。


提交網站審核通過後,可以查看其他大佬寫的代碼。(不知道有沒有直接看的方法,有的話請告知一下,(#^.^#))

這個題目的主要難點在於對字元創的匹配。關於這部分,大佬1的代碼極其簡潔,如下:

def song_decoder(song): return " ".join(song.replace(WUB, ).split())

使用到了replace split 以及join函數。下面將他的方法拆解一下。

第一步:song.replace(WUB, )的效果與re.sub(pattern_WUB, ,song) 是一樣的。

第二步:str.split()比較有意思。默認為所有的空字元,包括空格、換行(
)、製表符( )都將作為分割的依據。即多個空格將只分割一次。

當然,str.split(character,num)可以添加參數,第一個為分割依據,第二個為分割次數。即從左到右分割的次數,到達分割次數後就停止分割。例如:

A = WUBWUBaWUBaWUBaWUBcWUBcWUBWUBWUBcB = A.replace(WUB, )C = B.split( ,num)print(C)

num = 1,輸出結果為[, a a a c c c]

num = 2,輸出結果為[, , a a a c c c]

第三步:str.join(sequence)。將分割後的字元串重新用str連接起來。


還有的大佬2是這樣寫的:

def song_decoder(song): import re return re.sub((WUB)+, , song).strip()

這種方式綜合了我與大佬1的方法。


還有一位比較特立獨行的大佬3是這樣寫的:

def song_decoder(song): return .join([a for a in song.split(WUB) if a])

[a for a in song.split(WUB) if a]使用了布爾表達式。這是一種條件創建列表的方式。a是song字元串分割後的元素組成的列表,且元素需符合 if a,即返回TRUE。為什麼可以這樣呢?

在布爾操作的內容中,當控制流語句使用表達式時,以下值將被解釋為false:False,None,所有類型的數字零,以及空字元串和容器(包括字元串,元組,列表,字典 ,集和frozensets)。 所有其他值都被解釋為true。


def song_decoder(song): list = filter(lambda x: x != , song.split(WUB)) # Returning the joint items separed by spaces return .join(list)

filter() 函數用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。

該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。

關鍵字lambda表示匿名函數,冒號前面的x表示函數參數。

匿名函數有個限制,就是只能有一個表達式,不用寫return,返回值就是該表達式的結果。

用匿名函數有個好處,因為函數沒有名字,不必擔心函數名衝突。此外,匿名函數也是一個函數對象,也可以把匿名函數賦值給一個變數,再利用變數來調用該函數。


總結:Codewars非常適合提高代碼能力。因為題庫龐大,社區完善。

我是Python小白,歡迎討論交流!覺得有幫助請點贊支持哦。

參考資料:

匿名函數?

www.liaoxuefeng.com圖標Python strip()方法?

www.runoob.com

Python3 正則表達式 | 菜鳥教程?

www.runoob.com

Python split()方法?

www.runoob.com

輕鬆python文本專題-去掉字元串前後空格 - CSDN博客?

blog.csdn.net

Python filter() 函數?

www.runoob.com

Python join()方法 | 菜鳥教程?

www.runoob.com

Python判斷字元串與大小寫轉換_python_腳本之家?

www.jb51.net


推薦閱讀:

TAG:Python入門 | 字元串 | CodeWars |