入坑codewars第三天-Build a pile of Cubes、Convert boolean values to strings 'Yes' or 'No'、Build Tower

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_37341950/article/details/84427698

第一题:

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

猜你喜欢

转载自blog.csdn.net/sinat_37341950/article/details/84427698
今日推荐