Advertisement
acclivity

pyTraceAlphabet

Sep 1st, 2022 (edited)
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. # Trace the alphabet by moving Right, Down, Left and Up through a matrix
  2.  
  3. a = ["ACRFGHOT",
  4. "BCDEVIQR",
  5. "PXDUKJPQ",
  6. "FYASLOPQ",
  7. "RTVHMNSR",
  8. "YSZVVUTB",
  9. "MDYXWUPV",
  10. "REWQSDEF"]
  11. rows = len(a)
  12. cols = len(a[0])
  13.  
  14. letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ."
  15. idx = 0  # position within alphabet
  16. # note . as an end marker
  17.  
  18. # dict of x,y moves per direction
  19. # where x is column, y is row
  20. # e.g. Right adds 1 to x, y stays same
  21. dirs = {"R": (1, 0), "D": (0, 1), "L": (-1, 0), "U": (0, -1)}
  22.  
  23. x, y = -1, 0  # start 1 place to left of top left corner
  24.  
  25. # loop until all alphabet found
  26. while letters[idx] != ".":
  27.     for d in dirs.keys():     # R, D, L, U
  28.         # get moves for a direction
  29.         dx, dy = dirs[d]
  30.         # compute temporary next pos
  31.         dx += x
  32.         dy += y
  33.     # check column and row indexes are not out of bounds
  34.         if -1 < dx < cols and -1 < dy < rows:
  35.             # does this pos hold the next letter?
  36.             if a[dy][dx] == letters[idx]:
  37.                 break   # yes, quit inner loop
  38.                
  39.     print(d, letters[idx]) # show progress
  40.    
  41.     # confirm good position
  42.     x, y = dx, dy
  43.    
  44.     # bump idx to next letter
  45.     idx += 1       
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement