入坑codewars第九天-Title Case
題目:
Title Case
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.
###Arguments (Haskell)
- First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
- Second argument: the original string to be converted.
###Arguments (Other languages)
- First argument (required): the original string to be converted.
- Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass
undefined
when this argument is unused. -
###Example
title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
遺憾今天這題想得太複雜了沒完全通過,但是題意明白,後來看了最優解發現程式碼精簡,別人巧妙使用了列表推導式。
-
題意:
-
題目意思: 題意很簡單,就是輸入兩個字串,比如:x:'a clash of KINGS', y:'a an the of'; x中的單詞要是有y中的則不需要首字母大寫; 但是有一種情況就是剛好y中的某個單詞在x中是第一個單詞,則要大寫; 其他情況都是首字母大寫。
程式碼如下:
-
def title_case(title, minor_words=''):#這裡是設定minor_words預設值為空字串 #1.先將兩個字串轉成列表,並處理,minor中都是小寫,title中是先首字母大寫然後再分割 title = title.capitalize().split()#注意處理順序,先將首字母大寫,然後再分割 minor_words = minor_words.lower().split() #2.列表推導式處理 return ' '.join(words if words in minor_words else words.capitalize() for words in title)
在這裡我想說列表推導式很厲害。這裡列表推導式我是分三段理解。
-
第一段是固定格式,第二段是加了條件,第三段也是固定格式;
-
(1)選擇words單詞連線
-
(2)如果words在minor_words中則選擇minor_words中的此詞;否則將words做首字母大寫處理
-
(3)words都來自title相當於第一層迴圈
-
---------------------------------------------------------------
-
每一個句子的首字母都要大寫這個問題在程式碼第一步就處理了; title = title.capitalize().split(),第一步就把第一個字母大寫了,考慮了這種情況:(‘ab’,‘ab’)——>'Ab'