01_taxicab.py 685 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import sys
  3. def walk(instructions):
  4. x = y = 0
  5. dx = 0
  6. dy = -1
  7. yield x, y
  8. for turn, distance in instructions:
  9. if turn == 'L':
  10. dy, dx = -dx, dy
  11. elif turn == 'R':
  12. dy, dx = dx, -dy
  13. for i in range(distance):
  14. x += dx
  15. y += dy
  16. yield x, y
  17. def dist(x, y):
  18. return abs(x) + abs(y)
  19. instructions = [(w[0], int(w[1:])) for w in sys.stdin.readline().split(', ')]
  20. # part 1
  21. for pos in walk(instructions):
  22. pass
  23. print(dist(*pos))
  24. # part 2
  25. visited = set()
  26. for pos in walk(instructions):
  27. if pos in visited:
  28. break
  29. visited.add(pos)
  30. print(dist(*pos))