day6.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. with open(os.path.join(os.path.dirname(__file__), "example.txt")) as example:
  3. example_data = example.read().splitlines()
  4. with open(os.path.join(os.path.dirname(__file__), "input.txt")) as example:
  5. input_data = example.read().splitlines()
  6. def part1(data):
  7. problems = []
  8. for problem in data[:-1]:
  9. problems.append([int(d) for d in problem.split()])
  10. mo = data[-1].split()
  11. sum = 0
  12. for row in range(len(mo)):
  13. sp = 1 if mo[row] == "*" else 0
  14. for problem in problems:
  15. sp = sp * problem[row] if mo[row] == "*" else sp + problem[row]
  16. sum += sp
  17. print(f"Part1: {sum=}")
  18. def bench(part):
  19. import time
  20. def wrapper(*args, **kwargs):
  21. start = time.perf_counter()
  22. value = part(*args, **kwargs)
  23. print(f"\tevaluation time: {time.perf_counter() - start} s")
  24. return value
  25. return wrapper
  26. @bench
  27. def part2(data):
  28. # get the max numer of tens in each colums
  29. mo = data[-1].split()
  30. tens = [list(map(len, row.split())) for row in data[:-1]]
  31. max_tens = []
  32. for i in range(len(mo)):
  33. pipi = []
  34. for ten in tens:
  35. pipi.append(ten[i])
  36. max_tens.append(max(pipi))
  37. # get the numbers in colums with respect of tens and position of digits
  38. cursor = 0
  39. problems = []
  40. for tens in max_tens:
  41. digits = []
  42. for problem in data[:-1]:
  43. digits.append((problem[cursor : cursor + tens]))
  44. problems.append(digits)
  45. cursor += tens + 1
  46. # get the result calculating digits in column with respect of tens
  47. sum = 0
  48. for problem, m in zip(problems, mo):
  49. sp = 1 if m == "*" else 0
  50. for i in range(len(problem[0])):
  51. num = ""
  52. for nums in problem:
  53. digit = nums[i]
  54. num += digit
  55. if m == "*":
  56. sp = sp * int(num)
  57. else:
  58. sp = sp + int(num)
  59. sum += sp
  60. print(f"Part2: {sum=}")
  61. part1(example_data)
  62. part1(input_data)
  63. part2(example_data)
  64. part2(input_data)