[Solved] How to write a program to print the hollow diamond pattern similar to the pattern shown? [closed]


There are 2 things we need to consider. Lets say the number given was 30, this means the alphabets should round around and repeat. When we have this situation, we need a modulus which is % in python.

The other thing is how do we centre the string? In python, there’s a string method called center which takes an integer specifying the length of the centered string and also an optional argument which is set to space which is what we need.

Looking at the diamonds you have in the question, we can observe a pattern. The max length is the nth odd number which can be found with this formula: Nth odd number = N*2-1

This is the same for the number of spaces between the 2 characters in each row.

How do we get the characters? We can do this easily with the chr function which converts ascii character values to an actual character. Looking at the ascii table, capital alphabets start with code 65. Using this we can create this code for handling the alphabets. chr(n%26+65)

So, here’s the code:

row = int(input(': '))

n = row*2-1  # The length to center the string with.

# Upper part of diamond
for i in range(row):
    if i == 0:  # if it is the first iteration, then print out 1 character only centered
        print('A'.center(n))
        continue  # skip this iteration. essentially skipping the latter code.
    character = chr(i%26+65)  # the character to be used for the sides.
    print(f"{character}{' '*(2*i-1)}{character}".center(n))  # printing the line itself. if you didn't know, you can multiply strings with integers to result in that character/string being repeated integer times.

# Lower part of the diamond. Same thing as above, but mirrored.
for i in range(0, row-1)[::-1]:
    if i == 0:
        print('A'.center(n))
        continue
    character = chr(i%26+65)
    print(f"{character}{' '*(2*i-1)}{character}".center(n))

That’s all! Happy coding!

3

solved How to write a program to print the hollow diamond pattern similar to the pattern shown? [closed]