a.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os, argparse
  2. import numpy as np
  3. debug_print = print
  4. debug_print = lambda x: x
  5. def solve_task(lines):
  6. s = Snake()
  7. s.print()
  8. for line in lines:
  9. s.do(line)
  10. #s.print()
  11. print(len(s.visited))
  12. class Snake:
  13. def __init__(self):
  14. self.H = np.array([0, 0])
  15. self.last_H = self.H
  16. self.T = np.array([0, 0])
  17. self.visited = set()
  18. self.visited.add((0,0))
  19. def print(self):
  20. print(f"H: {self.H}, T: {self.T}")
  21. print(self.visited)
  22. def do(self, instruction):
  23. command = instruction.split(' ')[0]
  24. distance = int(instruction.split(' ')[1])
  25. for _ in range(distance):
  26. self.go(command)
  27. self.adjust_tail()
  28. def go(self, direction):
  29. debug_print(f"Moving {direction}")
  30. self.last_H = self.H.copy()
  31. if direction == 'R':
  32. self.H[0] += 1
  33. elif direction == 'L':
  34. self.H[0] -= 1
  35. elif direction == 'U':
  36. self.H[1] += 1
  37. elif direction == 'D':
  38. self.H[1] -= 1
  39. def adjust_tail(self):
  40. debug_print(f"Euclidian distance from T:{self.T} to H:{self.H} is {np.linalg.norm(self.H - self.T)}")
  41. if np.linalg.norm(self.H - self.T) >= 2:
  42. debug_print(f"Tail moving from {self.T} to {self.last_H}")
  43. self.T = self.last_H
  44. self.visited.add(tuple(self.T))
  45. else:
  46. debug_print(f"Tail not moving from {self.T} to {self.last_H}")
  47. def read_lines(filename):
  48. lines = []
  49. with open(filename) as infile:
  50. for raw_line in infile:
  51. line = raw_line.rstrip()
  52. lines.append(line)
  53. return lines
  54. def parse_arguments():
  55. parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
  56. parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
  57. args = parser.parse_args()
  58. return args
  59. def main():
  60. args = parse_arguments()
  61. lines = read_lines(args.filename)
  62. solve_task(lines)
  63. if __name__ == "__main__":
  64. main()