请实现一个函数,接收一个0~100内的整数n,返回一颗高度为n,且每一层宽度相同的圣诞树。非*号部分使用空格填充。
例如:height=5
时,返回:
*
***
*****
*******
*********
题目难度:中等
题目来源:codewars
def xmas_tree(height):
pass
assert xmas_tree(1) == '*'
assert xmas_tree(3) == ' * \n *** \n*****'
assert xmas_tree(5) == ' * \n *** \n ***** \n ******* \n*********'
def xmas_tree(height):
tree = ""
for i in range(height):
for j in range(height*2 - 1):
if (height+i) > j >= (height-i-1):
tree += "*"
else:
tree += " "
tree += "\n"
return tree[:-1]
# print(xmas_tree(5))
assert xmas_tree(1) == '*'
assert xmas_tree(2) == ' * \n***'
assert xmas_tree(5) == ' * \n *** \n ***** \n ******* \n*********'
def xmas_tree(height):
tree = ""
for i in range(height):
for j in range(height*2 - 1):
if abs(j - height) < i:
tree += "*"
else:
tree += " "
tree += "\n"
return tree[:-1]
def xmas_tree(height):
total = height - 1
result = []
for i in range(height):
result.append(total * " " + (2*(i + 1)-1) * "*" + total * " ")
total -= 1
return "\n".join(result)
assert xmas_tree(1) == '*'
print(xmas_tree(5))
assert xmas_tree(3) == ' * \n *** \n*****'
assert xmas_tree(5) == ' * \n *** \n ***** \n ******* \n*********'
肝!
def xmas_tree(num):
i = 1
while i <= num:
j = 1
temp=""
temp1=""
k=1
while k<=num-i:
temp1 += " "
k+=1
while j<=2i-1:
temp=temp+" "
j+=1
print(temp1,temp)
i += 1
while 1:
num=int(input(“请输入一个整数n”))
xmas_tree(num)
fwj
(fwj)
2021 年7 月 8 日 10:02
9
感觉就是找规律啊,不知道对不对
def fn(n):
res=''
for i in range(n):
if i<n-1:
a=(' '*(n-i-1)+'*'*(2*i+1)+' '*(n-i-1)+'\n')
res=res+a
else:
a=(' '*(n-i-1)+'*'*(2*i+1)+' '*(n-i-1))
res=res+a
return res
assert fn(5)==' * \n *** \n ***** \n ******* \n*********'
@Amoyshmily 小佛老师 [’ '*blank_num]*2 此处为什么要×2 没理解
Hi。乘以2是因为这里操作的是空格,每一行是*号在中间,被左右两边的空格包围。所以每边的空格当成一个整体,一共是2个这样的空格整体。