xyz_utils.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import collections
  2. def get_positions_from_str_representation(str_representation):
  3. # TODO: Manage z axis (like ------------ as separator)
  4. lines = str_representation.split("\n") # One item per lines
  5. lines = map(lambda l: l.strip().replace(' ', ''), lines) # Remove spaces
  6. lines = filter(lambda l: bool(l), lines) # Only line with content
  7. lines = list(lines)
  8. width = len(lines[0])
  9. height = len(lines)
  10. if not width % 2 or not height % 2:
  11. raise Exception(
  12. 'Width and height of your representation must be odd. '
  13. 'Actually it\'s {0}x{1}'.format(
  14. width,
  15. height,
  16. ))
  17. items_positions = collections.defaultdict(list)
  18. start_x = - int(width / 2 - 0.5)
  19. start_y = - int(height / 2 - 0.5)
  20. start_z = 0
  21. current_y = start_y
  22. current_z = start_z
  23. for line in lines:
  24. current_x = start_x
  25. for char in line:
  26. items_positions[char].append((
  27. current_x,
  28. current_y,
  29. current_z,
  30. ))
  31. current_x += 1
  32. current_y += 1
  33. return items_positions
  34. def get_str_representation_from_positions(
  35. items_positions: dict,
  36. separator='',
  37. tabulation='',
  38. start_with='',
  39. end_with='',
  40. ) -> str:
  41. positions = []
  42. for item_positions in items_positions.values():
  43. positions.extend(item_positions)
  44. positions = sorted(positions, key=lambda p: (p[2], p[1], p[0]))
  45. str_representation = start_with + tabulation
  46. start_x = positions[0][0]
  47. start_y = positions[0][1]
  48. start_z = positions[0][2]
  49. current_y = start_y
  50. current_z = start_z
  51. for position in positions:
  52. item = None
  53. for parsed_item in items_positions:
  54. if position in items_positions[parsed_item]:
  55. item = parsed_item
  56. break
  57. if position[1] != current_y:
  58. str_representation += "\n" + tabulation
  59. if position[2] != current_z:
  60. str_representation += '----' + "\n" + tabulation
  61. added_value = item
  62. if position[0] != start_x:
  63. added_value = separator + added_value
  64. str_representation += added_value
  65. current_y = position[1]
  66. current_z = position[2]
  67. return str_representation + end_with