Advertisement
CodingComputing

*Spiral Alphabet Pattern* Solution from @CodingComputing

Mar 28th, 2024 (edited)
956
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. # *Spiral Alphabet Pattern* Solution from @CodingComputing
  2. from string import ascii_uppercase
  3. letters = ascii_uppercase  # A string of 26 uppercase letters
  4.  
  5. rows, cols = 8, 8
  6. # Create matrix of empty strings of given dimension
  7. matrix = [["" for _ in range(cols)] for _ in range(rows)]
  8.  
  9. # Specify movement directions in clockwise order
  10. dirs = [ (1,0),   (0,1),   (-1,0),  (0, -1)]
  11. #       0:RIGHT  1:DOWN   2:LEFT    3.UP      (in clockwise order)
  12.  
  13. # Initialize position and direction
  14. x_next, y_next = 0, 0  # Start at top-left of matrix
  15. curr_dir = 0  # Start with moving rightwards
  16.  
  17. # Iterate n over
  18. for n in range(rows*cols):
  19.     x, y = x_next, y_next  # Update position
  20.     matrix[y][x] = letters[n%26]  # Fill in the letter
  21.     x_next = x + dirs[curr_dir][0]  # Propose new x based on current direction
  22.     y_next = y + dirs[curr_dir][1]  # Propose new y based on current direction
  23.     # IF there is a problem with the proposed update, cycle through direction
  24.     if not (0<=x_next<rows and 0<=y_next<cols and not matrix[y_next][x_next]):
  25.         curr_dir = (curr_dir + 1)%4  # Turn 90 degrees clockwise
  26.         x_next = x + dirs[curr_dir][0] # New x based on corrected direction
  27.         y_next = y + dirs[curr_dir][1] # New y based on corrected direction
  28.  
  29. # Join matrix into a single string and print it
  30. print("\n".join([" ".join(matrix[row]) for row in range(rows)]))
  31.  
  32. # OUTPUT:
  33. # A B C D E F G H
  34. # B C D E F G H I
  35. # A V W X Y Z I J
  36. # Z U H I J A J K
  37. # Y T G L K B K L
  38. # X S F E D C L M
  39. # W R Q P O N M N
  40. # V U T S R Q P O
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement