[英]print triangle pyramid using python with given value
I have printed a triangle pyramid like this:我打印了一个像这样的三角形金字塔:
*
* *
* * *
* * * *
* * * * *
My code is:我的代码是:
for i in range(1,6):
for j in range(6-i):
print(" ", end="")
for j in range(i):
print("*", end=" ")
print()
I want to print a triangle like this star pyramid: If I input 1: print first image then if I input 2 print second one.我想打印一个像这个星形金字塔这样的三角形:如果我输入 1:打印第一个图像然后如果我输入 2 打印第二个。 I want to know the actual logic.
我想知道实际的逻辑。
Considering the scalability of code, I have define two paramters, size
and layer
:考虑到代码的可扩展性,我定义了两个参数,
size
和layer
:
size
is height of triangle also star numbers of bottom size
是三角形的高度也是底部的星号layer
is layer of triangles you want to pile up layer
是你想要堆积的三角形层Here are some keypoints:以下是一些关键点:
str.center
is very helpful here. str.center
在这里非常有帮助。 If we know the width
, it can automaticly put it in the middle of it.如果我们知道
width
,它可以自动将其放在中间。 so with help of center
, if we calculate the star number and margine
between them.所以在
center
帮助下,如果我们计算它们之间的星数和margine
。 we can build a triangle easily.我们可以很容易地建立一个三角形。
implement the function to produce a single triangle: first print top
, then body
, last bottom
.实现生成单个三角形的函数:首先打印
top
,然后是body
,最后是bottom
。
compose single triangles together in same layer, layer 0 has 1 triangle, layer 1 has 2 triangles... we can just calculate the number of triangles in current layer and concat them by corresponding string, and then use total_width
to put them in center again.在同一层将单个三角形组合在一起,第0层有1个三角形,第1层有2个三角形......我们可以计算当前层的三角形数量并通过相应的字符串连接它们,然后使用
total_width
再次将它们放在中心.
Here is my solution:这是我的解决方案:
from functools import reduce
def generate_triangle(size, width):
res = []
# print top
res.append('*'.center(width))
# print body
margin = 1
for i in range(size - 2):
res.append(('*' + ' ' * margin + '*').center(width))
margin += 2
# print bottom
res.append(' '.join('*' * size).center(width))
return res
def generate_triangles(size, layer):
width = size * 2 - 1
total_width = layer * (width + 1) - 1
res = []
for i in range(layer):
res += reduce(lambda x, y: x + [' '.join(y for _ in range(i + 1)).center(total_width)],
generate_triangle(size, width), [])
return res
test code:测试代码:
def triangle_test():
def print_matrix(matrix):
for row in matrix:
print(row)
print()
print_matrix(generate_triangles(6, 1))
print_matrix(generate_triangles(5, 2))
print_matrix(generate_triangles(4, 4))
output:输出:
*
* *
* *
* *
* *
* * * * * *
*
* *
* *
* *
* * * * *
* *
* * * *
* * * *
* * * *
* * * * * * * * * *
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* * *
* * * * * *
* * * * * *
* * * * * * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Hope that will help you, and comment if you have further questions.希望能帮到你,还有什么问题可以评论。 : )
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.