How to do Alphabetic Spiral in python?

131 Views Asked by At

-- THE QUESTION --

Input : 3

Output :

A B C

H I D

G F E

Input : 5 Output :

A B C D E

P Q R S F

O X Y T G

N W V U H

M L K J I

-- My progress: --

print("input :")
n = int(input())

alphabet= 65
for i in range(n):
    print((n+i)*" ")
    for j in range(i, i+n):
        print(chr(alphabet), end=" ")
        alphabet = alphabet + 1
print()

Input : 5

Output :

A B C D E

F G H I J

K L M N O

P Q R S T

U V W X Y

Input : 3

Output :

A B C

D E F

G H I

1

There are 1 best solutions below

0
gimix On

This is not so trivial as it may seem. Anyway, here's a very simplistic solution:

  • build an alphabet long enough (I repeated the ASCII uppercase letters as needed so we can build spirals of any size)
  • create a matrix in memory with each letter in the right position
  • print the matrix

The code:

from string import ascii_uppercase

def spiral(n):
    alphabet = ascii_uppercase * (n**2//26+1) #repeat ABC..XYZ until needed
    alphabet = alphabet[:n**2] #take only n**2 chars
    ln = len(alphabet)
    grid = []
    for _ in range(n):
        grid.append([' ']*n)
    min_row = 0
    min_col = 0
    max_row = n
    max_col = n
    i = 0
    while i < ln:
        #left to right
        row = min_row
        for col in range(min_col, max_col):
            if i == ln:
                break
            grid[row][col] = alphabet[i]
            i += 1
        min_row += 1
        #top to bottom
        col = max_col-1
        for row in range(min_row, max_row):
            if i == ln:
                break
            grid[row][col] = alphabet[i]
            i += 1
        max_col -= 1
        #right to left
        row = max_row-1
        for col in range(max_col-1, min_col-1, -1):
            if i == ln:
                break
            grid[row][col] = alphabet[i]
            i += 1
        max_row -= 1
        #bottom to top
        col = min_col
        for row in range(max_row-1, min_row-1, -1):
            if i == ln:
                break
            grid[row][col] = alphabet[i]
            i += 1
        min_col += 1
    #print grid
    for row in range(n):
        for col in range(n):
            print(grid[row][col], end=' ')
        print()
        
>>> spiral(3)
A B C 
H I D 
G F E 

>>> spiral(9)
A B C D E F G H I 
F G H I J K L M J 
E D E F G H I N K 
D C T U V W J O L 
C B S B C X K P M 
B A R A Z Y L Q N 
A Z Q P O N M R O 
Z Y X W V U T S P 
Y X W V U T S R Q