Alphabet Rangoli

  • + 1 comment

    For what it's worth, here is my solution in Python 2. I did NOT focus on getting it as short as possible, since that tends to also make it confusing -- instead, I focussed on making it as simple/understandable as possible.

    from string import ascii_lowercase as letters
    # ascii_lowercase, i.e. letters, is the following string: 'abcdefghijklmnopqrstuvwxyz'
    
    def build_line(i, char_list):
        
        # Eg. If i = 2 and size = 5 ...
        
        # ... reduced_list = [e, d]
        reduced_list = char_list[ : i]
       
        # ... reversed_reduced_list = [d, e]
        reversed_reduced_list = reduced_list[: : -1]
       
        # ... reduced_list = [e, d, c]
        reduced_list.append(char_list[i])
       
        # ... reduced_list = [e, d, c, d, e]
        reduced_list.extend(reversed_reduced_list)
        
        # ... curr_baseline = 'e-d-c-d-e'
        curr_baseline = DASH.join(curr_baseline_list)
        
        # Eg. If line_length = 17, then we are saying:   print '{:-^17}'.format(curr_baseline) 
        # which means that the resulting string has to be padded on the left and right with the character '-' such that the string curr_baseline is in the middle and the total length of the final string is 17.
        # This is the final string that is printed:   ----e-d-c-d-e----
        print '{:{}^{}}'.format(curr_baseline, DASH, line_length)
        
    DASH = '-'
    
    size = int(raw_input())
    
    # Formula for length of each line (including dashes) is: (2*x) - 1, where x = (2*(size-1)) + 1
    x = (2 * (size - 1)) + 1
    line_length = (2 * x) - 1
    
    char_list = []
    
    # Eg. If size = 5, values of letter_index are: 4, 3, 2, 1, 0
    for letter_index in range(size - 1, -1, -1):    
            char_list.append(letters[letter_index])
            
    # Eg. If size = 5, char_list is now [e, d, c, b, a]. Note that len(char_list) = size.
    
    # Eg. If size = 5, values of i: 0, 1, 2, 3, 4
    for i in range(size):
        build_line(i, char_list)
        
    # Eg. If size = 5, values of i: 3, 2, 1, 0
    for i in range(size - 2, -1, -1):
        build_line(i, char_list)