Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # *Spiral Alphabet Pattern* Solution from @CodingComputing
- from string import ascii_uppercase
- letters = ascii_uppercase # A string of 26 uppercase letters
- rows, cols = 8, 8
- # Create matrix of empty strings of given dimension
- matrix = [["" for _ in range(cols)] for _ in range(rows)]
- # Specify movement directions in clockwise order
- dirs = [ (1,0), (0,1), (-1,0), (0, -1)]
- # 0:RIGHT 1:DOWN 2:LEFT 3.UP (in clockwise order)
- # Initialize position and direction
- x_next, y_next = 0, 0 # Start at top-left of matrix
- curr_dir = 0 # Start with moving rightwards
- # Iterate n over
- for n in range(rows*cols):
- x, y = x_next, y_next # Update position
- matrix[y][x] = letters[n%26] # Fill in the letter
- x_next = x + dirs[curr_dir][0] # Propose new x based on current direction
- y_next = y + dirs[curr_dir][1] # Propose new y based on current direction
- # IF there is a problem with the proposed update, cycle through direction
- if not (0<=x_next<rows and 0<=y_next<cols and not matrix[y_next][x_next]):
- curr_dir = (curr_dir + 1)%4 # Turn 90 degrees clockwise
- x_next = x + dirs[curr_dir][0] # New x based on corrected direction
- y_next = y + dirs[curr_dir][1] # New y based on corrected direction
- # Join matrix into a single string and print it
- print("\n".join([" ".join(matrix[row]) for row in range(rows)]))
- # OUTPUT:
- # A B C D E F G H
- # B C D E F G H I
- # A V W X Y Z I J
- # Z U H I J A J K
- # Y T G L K B K L
- # X S F E D C L M
- # W R Q P O N M N
- # V U T S R Q P O
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement