5 Best Ways to Create a Rangoli Pattern with Python Using Alphabets

πŸ’‘ Problem Formulation: The task discussed in this article involves creating a Python program to print Rangoli patterns using the English alphabet. Rangoli is a traditional Indian form of art where patterns are created on the floor using materials like colored rice, dry flour, or flower petals. The input would be an integer representing the size of the Rangoli and the desired output is a symmetric pattern of English alphabets centered on the letter ‘a’.

Method 1: Using List Comprehension and String Formatting

The first method employs list comprehension to create lists of letters and then uses string formatting to arrange these lists into the Rangoli pattern. The pattern’s size is dynamically calculated based on the user input size.

Here’s an example:

def print_rangoli(size):
    alpha = 'abcdefghijklmnopqrstuvwxyz'[0:size]
    for i in range(size-1, -size, -1):
        x = abs(i)
        line = alpha[size:x:-1]+alpha[x:size]
        print("--"*x + '-'.join(line) + "--"*x)

print_rangoli(3)

Output:

--c--
b-c-b
a-b-c-b-a
b-c-b
--c--

This function print_rangoli starts by slicing the alphabet string to the specified size and loops through a range that goes up and down to form the diamond shape. With string joining and formatting, it then combines the letters into the required pattern centered on ‘a’.

Method 2: Using Double Iteration

This approach uses two nested loops to first print the upper half of the Rangoli, followed by the lower half, effectively building the pattern row by row.

Here’s an example:

def print_rangoli(size):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    L = []
    for i in range(size):
        s = "-".join(alpha[i:size])
        L.append((s[::-1]+s[1:]).center(4*size-3, "-"))
    print('\n'.join(L[:0:-1]+L))

print_rangoli(3)

Output:

--c--
b-c-b
a-b-c-b-a
b-c-b
--c--

The code snippet creates the Rangoli by first generating individual lines with centered text, concatenating the halves, and using string centering to align them properly. The mirror image is built with slicing and reversing the string.

Method 3: Recursive Approach

Here, a recursive function is implemented to print each line of the Rangoli pattern, which calls itself until it reaches the base case, and then it unwinds the recursion, finishing the pattern.

Here’s an example:

def print_rangoli_rec(size, current=0):
    if size == current:
        return []
    else:
        middle = '-'.join([chr(97 + size - i - 1) for i in range(current + 1)])
        sides = '-' * (2 * (size - current - 1))
        line = sides + middle + middle[::-1][1:] + sides
        return [line] + print_rangoli_rec(size, current + 1) + [line]

size = 3
print('\n'.join(print_rangoli_rec(size)))

Output:

--c--
b-c-b
a-b-c-b-a
b-c-b
--c--

Recursive calls build from the base case of the size of Rangoli up to building the complete Rangoli pattern. This approach leverages the symmetrical nature of the pattern by ensuring symmetry on either side of the center.

Method 4: Using itertools module

This method uses Python’s itertools module to generate the permutations required for the pattern. The itertools.chain method combines the required strings for each line before printing them out.

Here’s an example:

import itertools

def print_rangoli(size):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    for i in itertools.chain(range(size-1, -1, -1), range(1, size)):
        print("-".join(alpha[size-1:i:-1] + alpha[i:size]).center(4*size-3, "-"))

print_rangoli(3)

Output:

--c--
b-c-b
a-b-c-b-a
b-c-b
--c--

The print_rangoli function uses itertools.chain to print the upper and lower parts of the pattern in a simple loop, avoiding complex range calculations and reducing the overall complexity of the pattern generation.

Bonus One-Liner Method 5: List Comprehension with Join

A compact one-liner solution using list comprehension, the join method, and string centering to print the Rangoli pattern in a single print statement.

Here’s an example:

def print_rangoli(size):
    print('\n'.join('-'.join(chr(97+size-1-j) for j in range(i) for i in range(size-1, -size, -1)).center(4*size-3, '-') for i in range(size-1, -1, -1) for _ in range(2)))

print_rangoli(3)

Output:

--c--
b-c-b
a-b-c-b-a
b-c-b
--c--

This one-liner packs the logic of Rangoli generation into a single complex list comprehension that iterates in the required order and arranges characters and “-” separators, centered according to the size of the Rangoli.

Summary/Discussion

  • Method 1: List Comprehension with String Formatting. Strengths: It’s readable and straightforward, with explicit control over the pattern’s symmetry. Weaknesses: May not be as concise as other methods.
  • Method 2: Double Iteration. Strengths: It builds the pattern with clarity on line construction. Weaknesses: The nested loop increases complexity and might be less efficient.
  • Method 3: Recursive Approach. Strengths: Elegant and utilizes recursion fitting the pattern’s symmetrical nature. Weaknesses: More memory consumption due to call stack, and recursion may be slower for larger patterns.
  • Method 4: Using itertools. Strengths: Simplifies iteration logic with itertools tools leading to cleaner code. Weaknesses: Can be less intuitive for those unfamiliar with itertools.
  • Method 5: One-Liner. Strengths: Extremely compact, showcasing Python’s capabilities for concise code. Weaknesses: Reduced readability and maintainability due to complexity.