【问题标题】:python 3.10 codes如何在 python 3 中的矩形内定位 ascii 等腰金字塔?
【发布时间】:2022-10-05 06:23:29
【问题描述】:

我为一个空心矩形创建了一个代码,但我无法在矩形内放置一个直立的等腰金字塔。谁能帮助我如何在矩形内挤压金字塔的代码? 这是它应该看起来的样子 my code output vs. the right way

#here are the inputs: 
b = height of the rectangle
2*b-1 = width of the rectangle
a = height of the triangle

这是我的代码: 这个矩形的输出,下面是一个金字塔,这不是我想要的。

b = int(input(\'Enter b: \'))
a = int(input(\'Enter a:\\n\'))
horizontal = b
vertical = 2*b-1
height = (a)
#for the rectangle
for i in range (horizontal):
    for j in range(vertical):
           if(i == 0 or i == horizontal - 1 or j == 0 or j == vertical - 1):
         print(\'b\', end = \'\')
    else:
        print(\' \', end = \'\')
print()
#for the pyramid
for i in range (1, height-1):
    j = height - i
    print(\' \'*j+(2*i-1)*\'a\')
  • @MagnusO_O,谢谢。我已经编辑了我的问题,请随时提供帮助!

标签: python python-3.x helper


【解决方案1】:

在哪里一个是三角形的高度和b是矩形的高度:

rh = int(input('Enter b: '))    # Rectangle's height.
th = int(input('Enter a: '))    # Triangle's height.
rw = rh * 2 - 1                 # Rectangle's width.
print()
# Limit size of triangle (rectangle >= triangle).
if th > rh:
    th = rh
# Generate the rectangle as a matrix of chars.
rectangle = [['b'] * rw, ['b'] * rw]
for _ in range(rh - 2):
    rectangle.insert(1, (['b'] + ([' '] * (rw - 2)) + ['b']))
# Calculate gaps between rectangle and triangle.
gap1 = int((rh - th) / 2)       # Empty lines over the triangle.
gap2 = gap1                     # Empty lines below the triangle.
if (rh - th) & 1:
    gap2 = gap1 + 1
# Insert the triangle into the rectangle.
width = 1                       # Current width of the triangle.
for row in range(gap1, len(rectangle) - gap2):
    start = int(rw / 2) - (row - gap1)
    for i in range(start, start + width):
        rectangle[row][i] = 'a'
    width += 2
# Print the output matrix.
for row in rectangle:
    print(''.join(row))

请注意,三角形的大小仅限于矩形的大小! 所以,对于像这样的输入b=12a=8(就像你的图片一样),这是输出:

bbbbbbbbbbbbbbbbbbbbbbb
b                     b
b          a          b
b         aaa         b
b        aaaaa        b
b       aaaaaaa       b
b      aaaaaaaaa      b
b     aaaaaaaaaaa     b
b    aaaaaaaaaaaaa    b
b   aaaaaaaaaaaaaaa   b
b                     b
bbbbbbbbbbbbbbbbbbbbbbb

【讨论】:

  • 如果我不是那么具体,我很抱歉。 a 应该等于金字塔的高度而不是宽度。
  • 我编辑了我的问题@John85。请帮我修改你的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
相关资源
最近更新 更多