codewars 刷題

題目要求:

Description:
Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
Python: return a list;
JavaScript: returns an Array;
C#: returns a string[];
PHP: returns an array;
C++: returns a vector<string>;
Haskell: returns a [String];
Ruby: returns an Array;
Have fun!
for example, a tower of 3 floors looks like below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]

簡單來說就是函數(shù)返回一個(gè)列表,里面是一個(gè)等差數(shù)列組成的*,注意空格。

對python的基礎(chǔ)庫不太了解,用了個(gè)笨辦法解決:

def tower_builder(n_floors):
    # build here
    s = '*'
    e = s + (n_floors - 1) * 2 * s
    l = e.__len__()
    def space(n):
        m = (l - n) * 0.5
        return int(m) * ' '
    return [space(i) + i * s + space(i) for i in range(1, (n_floors+1)*2-1, 2)]

而且第一次犯了個(gè)錯(cuò)誤,都知道在python中可以這樣重復(fù)字符串,

image.png

float類型不能直接與字符串相乘,這樣會(huì)出錯(cuò):
image.png

return int(m) * ' ',如果沒做類型轉(zhuǎn)換,會(huì)出錯(cuò)的~

看到別人的解法,才知道原來string有個(gè)center方法,╮(╯▽╰)╭

def tower_builder(n):
    return [("*" * (i*2-1)).center(n*2-1) for i in range(1, n+1)]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容