b.py 4.5 KB

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