import re import argparse parser = argparse.ArgumentParser() parser.add_argument("filename", help="the file from which to take data") args = parser.parse_args() with open(args.filename, "r") as f: commands = f.readlines() visited = {(0,0)} head = (0, 0) tails = (0, 0) def walk(command, head, tail, visited): direction, repeats = command.split(" ") repeats = int(repeats) first = True while repeats > 0: head = step(direction, head, tail) tail = follow(head, tail) first = False visited = visited | {tail} repeats -= 1 print("walking {} while head is {} and tail is {}".format(command, head, tail)) return head, tail, visited def follow(head, tail): if head[0] < tail[0]-1 or head[0] > tail[0]+1 or \ head[1] < tail[1]-1 or head[1] > tail[1]+1: if head[0] < tail[0]: tail = (tail[0]-1, tail[1]) if head[0] > tail[0]: tail = (tail[0]+1, tail[1]) if head[1] < tail[1]: tail = (tail[0], tail[1]-1) if head[1] > tail[1]: tail = (tail[0], tail[1]+1) return tail def step(direction, head, tail): match direction: case 'R': return (head[0]+1, head[1]) case 'L': return (head[0]-1, head[1]) case 'U': return (head[0], head[1]+1) case 'D': return (head[0], head[1]-1) case _: return head print("{}".format(visited)) for command in commands: head, tail, visited = walk(command, head, tail, visited) print("{}".format(visited)) print("visited {} locations".format(len(visited)))