入坑codewars第三天-Build a pile of Cubes、Convert boolean values to strings 'Yes' or 'No'、Build Tower
第一題:
Build a pile of Cubes:
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-nb, findNb)
will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
簡單來說題意就是:比如findNb(1071225) --> 45
就是在1-1071225中找一個數n使得 n^3 + (n-1)^3 + ... + 1^3 = 1071225
二、解題:
一開始寫了兩個for迴圈發現速度很慢
後來參考別人的
發現可以用一個while迴圈就可以
程式碼如下:
def find_nb(m): mm=0 n=0 while mm<m: n=n+1 mm=mm+n**3 if mm==m: return n else: return -1
就是遍歷。之前沒想清楚走了彎路。
第二題:
一、題目
碰到一道超級簡單的題:
意思就是輸入True則輸出Yes,輸入False則輸出No
廢話不多說直接上圖:
def bool_to_word(boolean):
if boolean == True:
return 'Yes'
if boolean == False:
return 'No'
第三題:
一、題目:
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
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
Go challenge Build Tower Advanced once you have finished this :)
FUNDAMENTALSSTRINGSBASIC LANGUAGE FEATURES
題意就是:
輸入層數輸出金字塔輸出樣例如下:
思路:
觀察輸出可以知道:假如給定數字3
第一層是‘*’左邊兩個空格,‘*’右邊兩個空格,一個*號
第二層是‘*’左邊一個空格,右邊一樣,三個*
……
觀察空格數可以發現規律:
總層數n_floors,層數控制變數 i,空格數控制變數 j
層數:0 空格數 :2 —— j 從(i,n_floors-1)變化,空格數0,1,2
層數:1 空格數 :1
層數:2 空格數 :0
————————————————————————————————————————————————————————
觀察 * 號數:
總層數n_floors,層數控制變數 i,空格數控制變數 k
層數:0 * 數 :1 —— k從(0,2*i+1)變化,*號數
層數:1 * 數 :3
層數:2 * 數 : 5
因此程式碼如下:
def tower_builder(n_floors):
lst=[]
for i in range(0,n_floors):
str1=''
str2=''
for j in range(i,n_floors-1):
str1=str1+' '
for k in range(0,2*i+1):
str2=str2+'*'
lst.append(str1+str2+str1)
return lst