a.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os, argparse
  2. def solve_task(lines):
  3. c = CRT()
  4. signal_strengths = []
  5. for line in lines:
  6. signal_strengths.extend(c.parse_instruction(line))
  7. total = sum(signal_strengths)
  8. print(signal_strengths)
  9. print(f"Total signal strength: {total}")
  10. class CRT:
  11. def __init__(self):
  12. self.x = 1
  13. self.cycle = 0
  14. def parse_instruction(self, instruction):
  15. states_to_return = []
  16. tokens = instruction.split()
  17. if tokens[0] == "noop":
  18. states_to_return.extend(self.tick())
  19. else:
  20. xdiff = int(tokens[1])
  21. states_to_return.extend(self.tick())
  22. states_to_return.extend(self.tick())
  23. self.x += xdiff
  24. return states_to_return
  25. def tick(self):
  26. to_return = []
  27. self.cycle += 1
  28. if (self.cycle+20) % 40 == 0:
  29. to_return = [self.cycle*self.x]
  30. return to_return
  31. def read_lines(filename):
  32. lines = []
  33. with open(filename) as infile:
  34. for raw_line in infile:
  35. line = raw_line.rstrip()
  36. lines.append(line)
  37. return lines
  38. def parse_arguments():
  39. parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
  40. parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
  41. args = parser.parse_args()
  42. return args
  43. def main():
  44. args = parse_arguments()
  45. lines = read_lines(args.filename)
  46. solve_task(lines)
  47. if __name__ == "__main__":
  48. main()