題目要求:
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)]