Advertisement
gruntfutuk

matrix find

Jul 22nd, 2020
2,636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. def create_matrix(source):
  2.     matrix = []
  3.     for row in source.split('\n')[1:]:  # split string into list of strings on newline, and loop through each line
  4.         matrix.append(row[3:].split()) # split string from position 3 on space (default for split)
  5.     return matrix
  6.  
  7. def print_matrix(matrix):
  8.     print('   ', end="")
  9.     for idx in range(len(matrix[0])):
  10.         print(f'{idx: 2x} ', end="")
  11.  
  12.     print()
  13.     for idx, row in enumerate(matrix):
  14.         print(f'{idx * 10:0>2} ', end="")
  15.         for cell in row:
  16.             print(f'{cell:>2} ', end="")
  17.         print()
  18.  
  19. def find_target(matrix, target):
  20.     locations = []
  21.     for idx_r, row in enumerate(matrix):
  22.        for idx_c, cell in enumerate(row):
  23.         if cell == target:
  24.             locations.append((idx_r, idx_c))
  25.     return locations
  26.  
  27. def print_locations(locations):
  28.     for row, col in locations:
  29.         print(f'{row * 10:0>2}{col:0>2x}')
  30.  
  31. ss = """   0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
  32. 00 __ __ __ __ __ __ __ __ __ __ __ __ UU __ __ __
  33. 10 UU __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
  34. 20 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
  35. 30 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
  36. 40 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
  37. 50 __ __ __ __ __ __ __ __ UU __ __ __ __ __ __ __
  38. 60 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
  39. 70 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ """
  40.  
  41.  
  42. matrix = create_matrix(ss)
  43. print_matrix(matrix)
  44. locations = find_target(matrix, "UU")
  45. if locations:
  46.     print("\nTarget UU found in locations:-")
  47.     print_locations(locations)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement