Python program to print rangoli pattern using alphabets


Suppose we have a number n. We have to create alphabet rangoli of n x n size. n must be within 1 and 26 and it will start from a and end at z when n is 26.

So, if the input is like 5, then the output will be

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

To solve this, we will follow these steps −

  • for i in range n-1 to 0, decrease by 1, do
    • for j in range 0 to i-1, do
      • print "--"
    • for j in range n-1 to i+1, decrease by 1, do
      • print character whose ASCII is j+97 and print extra "-" at the end
    • for j in range i to n-1, do
      • if j is not same as n-1, then
        • print character whose ASCII is j+97 and print extra "-" at the end
      • otherwise,
        • print character whose ASCII is j+97
    • for j in range 0 to 2*i - 1, do
      • print "-" at the end
    • go for next line
  • for i in range 1 to n-1, do
    • for j in range 0 to i, do
      • print "--"
    • for j in range n-1 to i+1, decrease by 1, do
      • print character whose ASCII is j+97 and print extra "-" at the end
    • for j in range i to n-1, do
      • if j is not same as n-1, then
        • print character whose ASCII is j+97 and print extra "-" at the end
      • otherwise,
        • print character whose ASCII is j+97
    • for j in range 0 to 2*i - 1, do
      • print "-" at the end
    • go to the next line

Example

Let us see the following implementation to get better understanding

def solve(n):
   for i in range(n-1,-1,-1):
      for j in range(i):
         print(end="--")
      for j in range(n-1,i,-1):
         print(chr(j+97),end="-")
      for j in range(i,n):
         if j != n-1:
            print(chr(j+97),end="-")
         else:
            print(chr(j+97),end="")
      for j in range(2*i):
         print(end="-")
      print()
   for i in range(1,n):
      for j in range(i):
         print(end="--")
      for j in range(n-1,i,-1):
         print(chr(j+97),end="-")
      for j in range(i,n):
         if j != n-1:
            print(chr(j+97),end="-")
         else:
            print(chr(j+97),end="")
      for j in range(2*i):
         print(end="-")
   print()

n = 8
solve(n)

Input

8

Output

--------------h--------------
------------h-g-h------------
----------h-g-f-g-h----------
--------h-g-f-e-f-g-h--------
------h-g-f-e-d-e-f-g-h------
----h-g-f-e-d-c-d-e-f-g-h----
--h-g-f-e-d-c-b-c-d-e-f-g-h--
h-g-f-e-d-c-b-a-b-c-d-e-f-g-h
--h-g-f-e-d-c-b-c-d-e-f-g-h--
----h-g-f-e-d-c-d-e-f-g-h----
------h-g-f-e-d-e-f-g-h------
--------h-g-f-e-f-g-h--------
----------h-g-f-g-h----------
------------h-g-h------------
--------------h--------------

Updated on: 11-Oct-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements