a.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import os, argparse
  2. DEBUG = False
  3. #DEBUG = True
  4. def debug_print(s):
  5. if DEBUG:
  6. print(f"DEBUG: {s}")
  7. def solve_task(lines):
  8. monkeys = []
  9. current_monkey = []
  10. for line in lines:
  11. if len(line) == 0:
  12. monkeys.append(Monkey.from_line(current_monkey))
  13. current_monkey = []
  14. else:
  15. current_monkey.append(line)
  16. if(len(current_monkey) != 0):
  17. monkeys.append(Monkey.from_line(current_monkey))
  18. for i, monkey in enumerate(monkeys):
  19. print(f"Monkey {i}:")
  20. print(f"{monkey}\n")
  21. game = KeepAwayGame(monkeys)
  22. game.do_rounds(20)
  23. for i, monkey in enumerate(monkeys):
  24. print(f"Monkey {i} inspected items : {monkey.items_inspected} times.")
  25. print(f"Monkey business: {game.monkey_business()}")
  26. class KeepAwayGame:
  27. def __init__(self, monkeys) -> None:
  28. self.monkeys = monkeys
  29. def do_rounds(self, n = 1):
  30. for round in range(n):
  31. debug_print(f"Round {round}")
  32. for i, monkey in enumerate(self.monkeys):
  33. debug_print(f"Monkey {i}:")
  34. monkey.take_round(self.throw)
  35. def monkey_business(self):
  36. inspections = [m.items_inspected for m in self.monkeys]
  37. inspections.sort()
  38. return inspections[-1] * inspections[-2]
  39. def throw(self, recipient, worry_level):
  40. self.monkeys[recipient].give(worry_level)
  41. class Monkey:
  42. def __init__(self, items, operation, test, true_monkey, false_monkey) -> None:
  43. self._items = items
  44. self._operation = operation
  45. self._test = test
  46. self._true_monkey = true_monkey
  47. self._false_monkey = false_monkey
  48. self.items_inspected = 0
  49. def __str__(self):
  50. to_return = f" Items: {str(self._items)[1:-1]}\n"
  51. to_return += f" Operation: {self._operation}\n"
  52. to_return += f" Test: divisible by {self._test}\n"
  53. to_return += f" If true: throw to monkey {self._true_monkey}\n"
  54. to_return += f" If false: throw to monkey {self._false_monkey}"
  55. return to_return
  56. def give(self, item):
  57. self._items.append(item)
  58. def take_round(self, throw_function):
  59. while len(self._items):
  60. item = self._items.pop(0)
  61. #debug_print(f" Monkey inspects an item with a worry level of {item}.")
  62. self.items_inspected += 1
  63. item = self._operation(item)
  64. debug_print(f" New worry level: {item}.")
  65. item = item // 3
  66. #debug_print(f" Monkey gets bored with item. Worry level is divided by 3 to {item}.")
  67. if self._test(item):
  68. debug_print(f" Test: true")
  69. throw_function(self._true_monkey, item)
  70. #debug_print(f" Item with worry level {item} is thrown to monkey {self._true_monkey}.")
  71. else:
  72. #debug_print(f" Test: false")
  73. throw_function(self._false_monkey, item)
  74. #debug_print(f" Item with worry level {item} is thrown to monkey {self._false_monkey}.")
  75. def from_line(lines) -> None:
  76. starting_items = [int(i) for i in lines[1].split(':')[1].split(',')]
  77. operation = Monkey.create_operation_from_line(lines[2])
  78. test = lambda x: x%int(lines[3].split("by")[1]) == 0
  79. iftrue = int(lines[4].split("monkey")[1])
  80. iffalse = int(lines[5].split("monkey")[1])
  81. return Monkey(starting_items, operation, test, iftrue, iffalse)
  82. def create_operation_from_line(line):
  83. operation = line.split(':')[1].strip()
  84. global_dir = {}
  85. exec(f"""def func(old):
  86. {operation}
  87. return new""", global_dir)
  88. return global_dir["func"]
  89. def read_lines(filename):
  90. lines = []
  91. with open(filename) as infile:
  92. for raw_line in infile:
  93. line = raw_line.rstrip()
  94. lines.append(line)
  95. return lines
  96. def parse_arguments():
  97. parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
  98. parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
  99. args = parser.parse_args()
  100. return args
  101. def main():
  102. args = parse_arguments()
  103. lines = read_lines(args.filename)
  104. solve_task(lines)
  105. if __name__ == "__main__":
  106. main()