ascii pattern in pyhton

Question:

I created a code for a hollow rectangle but i’m having trouble putting putting an upright isosceles pyramid inside the rectangle. can anyone help how can I squeeze the code for a pyramid inside a rectangle?
here is what it supposed to look like
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

here is my code:
the output of this a rectangle and below it a pyramid which is not what i intended.

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')
Asked By: ashley jacob

||

Answers:

Where a is the height of the triangle and b is the height of the rectangle:

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))

Note that the size of the triangle is limited to the size of the rectangle!
so, for an input like b=12 and a=8 (like in your image), this is the output:

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
Answered By: John85
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.