main.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import os, sys
  2. task_dir = os.path.dirname(__file__)
  3. sys.path.append(f'{task_dir}/..')
  4. from get_tasks import get_input, check_example, generate_readme
  5. def part1(input: list[str]):
  6. count = 0
  7. for line in input:
  8. line = line.split()[11:]
  9. for comb in line:
  10. match len(comb):
  11. case 2 | 3 | 4 | 7: count += 1
  12. print('The answer of part1 is:', count)
  13. def part2(input: list[str]):
  14. numbers = []
  15. for lines in input:
  16. six, five = [], []
  17. for comb in lines.split()[:10]:
  18. match len(comb):
  19. case 2: one = set(comb)
  20. case 3: seven = set(comb)
  21. case 4: four = set(comb)
  22. case 7: eight = set(comb)
  23. case 6: six.append(set(comb))
  24. case 5: five.append(set(comb))
  25. three = [i for i in five if len(i - one) == 3].pop()
  26. five.pop(five.index(three))
  27. a = (seven - one)
  28. g = three - four - seven
  29. b = four - three
  30. e = eight - four - a - g
  31. d = eight - a - b - e - g - one
  32. if (five[0] - three) == b:
  33. f = five[0] & one
  34. c = one - f
  35. else:
  36. c = five[0] & one
  37. f = one - c
  38. two = a | c | d | e | g
  39. five = a | d | f | g | b
  40. six = a | b | d | e | f | g
  41. nine = a | b | c | d | f | g
  42. zero = eight - d
  43. num = ""
  44. for comb in lines.split()[11:]:
  45. if (val := set(comb)) == zero : num += '0'
  46. elif val == one: num += '1'
  47. elif val == two: num += '2'
  48. elif val == three: num += '3'
  49. elif val == four: num += '4'
  50. elif val == five: num += '5'
  51. elif val == six: num += '6'
  52. elif val == seven: num += '7'
  53. elif val == eight: num += '8'
  54. elif val == nine: num += '9'
  55. else : raise Exception("There is no such code")
  56. numbers.append(int(num))
  57. print('The answer of part2 is:', sum(numbers))
  58. if __name__ == "__main__":
  59. input, example = get_input(task_dir, 8)
  60. check_example(example, part1)
  61. check_example(example, part2)
  62. part1(input)
  63. part2(input)
  64. generate_readme(task_dir, 8)