def test_should_return_1941_for_first_exercise(self): # given file_reader = FileReader('./input') instructions = file_reader.to_str_list() # when accumulator = run_console(instructions)['accumulator'] # then assert accumulator == 1941
if unit == 'in': if height > 76 or height <= 59: return False if unit == 'cm': if height < 150 or height > 193: return False if fields['hcl']: if not re.match('#[\da-f]{6}', fields['hcl']): return False if fields['ecl']: authorized_colors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'] if fields['ecl'] not in authorized_colors: return False if fields['pid']: if not re.match('^\d{9}$', fields['pid']): return False return True if __name__ == '__main__': file_reader = FileReader('./input') passports = file_reader.to_str_list('\n\n') print([is_passport_valid(passport) for passport in passports].count(True))
if matching_value in self.rows: return [entry, matching_value] return [] def findMatchingTriplet(self) -> List[int]: VALUE_TO_FIND = 2020 for index, initial_entry in enumerate(self.rows): remaining_entries = self.rows[index + 1:] for second_entry in remaining_entries: matching_value = VALUE_TO_FIND - initial_entry - second_entry if matching_value in self.rows: return [initial_entry, second_entry, matching_value] return [] def get_result(self) -> int: return reduce((lambda x, y: x * y), self.findMatchingPair()) def get_result_for_triplet(self) -> int: return reduce((lambda x, y: x * y), self.findMatchingTriplet()) if __name__ == '__main__': file_reader = FileReader('./input') list_of_expenses = file_reader.to_int_list() expense_book = ExpenseBook(list_of_expenses) print(expense_book.get_result()) print(expense_book.get_result_for_triplet())
def is_password_valid(self, password) -> True: password_letters = list(password) is_first_position_match_letter = password_letters[self.first_position - 1] == self.letter_checked is_second_position_match_letter = password_letters[self.second_position - 1] == self.letter_checked if is_first_position_match_letter and is_second_position_match_letter: return False if is_first_position_match_letter or is_second_position_match_letter: return True return False @staticmethod def parse_registry(registry: str) -> ('Policy', str): [raw_policy, password] = registry.split(':') [occurences, letter] = raw_policy.split() [first, second] = occurences.split('-') return Policy(letter_checked=letter, first_position=int(first), second_position=int(second)), password.strip() if __name__ == '__main__': if __name__ == '__main__': file_reader = FileReader('./input') password_registry = file_reader.to_str_list() parsed_registry = [Policy.parse_registry(line) for line in password_registry] print(count_valid_password(parsed_registry))
def fix_instructions(instructions: List[str]): alternative_instructions = [instructions] for i, value in enumerate(instructions): copy = instructions.copy() (instruction, offset) = copy[i].split() if instruction == 'jmp': instruction = 'nop' elif instruction == 'nop': instruction = 'jmp' copy[i] = ' '.join([instruction, offset]) alternative_instructions.append(copy) for instruction in alternative_instructions: execution_trace = run_console(instruction) if execution_trace['has_failed'] is False: return execution_trace if __name__ == '__main__': file_reader = FileReader('./input') instructions = file_reader.to_str_list() print(f"Accumulator 🤖 - {run_console(instructions)['accumulator']}") print( f"Fixed accumulator 🤖 - {fix_instructions(instructions)['accumulator']}" )
from common.file_reader import FileReader def count_unique_answers(answers: str) -> int: given_answers = [answer.strip() for answer in answers.strip()] unique_answers = set(itertools.chain(*given_answers)) return len(unique_answers) def count_answers_where_everyone_says_yes(answers: str) -> int: answers_by_people = [set(list(answer)).intersection() for answer in answers.split()] return len(answers_by_people[0].intersection(*answers_by_people)) def count_total_answers(answers_by_group) -> int: return sum([count_unique_answers(group) for group in answers_by_group]) def count_total_answers_part_2(answers_by_group) -> int: return sum([count_answers_where_everyone_says_yes(group) for group in answers_by_group]) if __name__ == '__main__': file_reader = FileReader('./input') answers_by_group = file_reader.to_str_list('\n\n') print(count_total_answers(answers_by_group)) print(count_total_answers_part_2(answers_by_group))
break position_down = position_down + trajectory.down position_right = position_right + trajectory.right next_element = map.check_position(down=position_down, right=position_right) if next_element == '#': counted_trees = counted_trees + 1 return counted_trees if __name__ == '__main__': file_reader = FileReader('./input') slope_plan = file_reader.to_str_list() map = Map(pattern=slope_plan) slope_1 = Trajectory(right=1, down=1) slope_2 = Trajectory(right=3, down=1) slope_3 = Trajectory(right=5, down=1) slope_4 = Trajectory(right=7, down=1) slope_5 = Trajectory(right=1, down=2) print('Exercise 1') print(count_trees_on_the_slope(map, slope_2)) print('Exercise 2') print(count_trees_on_the_slope(map, slope_1)) print(count_trees_on_the_slope(map, slope_2))
positions = iter(self._sequence.strip()[7:]) while True: try: position = next(positions) is_upper_half = position.startswith('L') limit = int(len(rows) / 2) if is_upper_half: rows = rows[0:limit] else: rows = rows[limit:] except StopIteration: break return max(rows) def get_seat_id(self) -> int: return self.get_row() * 8 + self.get_column() if __name__ == '__main__': file_reader = FileReader('./input') sequences = file_reader.to_str_list() list_of_seats_id = [BoardingPass(sequence).get_seat_id() for sequence in sequences] max_seat_id = max(list_of_seats_id) print(f"Max Seat ID : {max_seat_id}") print(f"My Seat ID : {find_missing_boarding_pass(list_of_seats_id)}")
count = {0: 1} for adapter in adapters: count[adapter] = 0 if adapter - 1 in count: count[adapter] += count[adapter - 1] if adapter - 2 in count: count[adapter] += count[adapter - 2] if adapter - 3 in count: count[adapter] += count[adapter - 3] return count[max(count)] if __name__ == '__main__': file_reader = FileReader('./input.txt') adapters = file_reader.to_int_list() bag = Bag(adapters) print( f"⚡️ Counting adapters with 1 difference : {bag.count_jolt_differences(1)}" ) print( f"⚡️ Counting adapters with 3 difference : {bag.count_jolt_differences(3)}" ) print( f"Multiplied : {bag.count_jolt_differences(1) * bag.count_jolt_differences(3)}" ) print(f"Possible ways : {bag.count_possible_ways_v2()}")
def _parse_rule(rule) -> (str, dict): bag_color_regex = '[a-zA-Z]+ [a-zA-Z]+' bags_under_condition = re.search(f"({bag_color_regex})", rule).group(1) no_rules_for_bag = re.search('contain no other bags.$', rule) rules_for_bag = {} if no_rules_for_bag: pass else: bag_rules = re.findall(f"([0-9]) ({bag_color_regex})", rule) for bag_rule in bag_rules: quantity = int(bag_rule[0]) color = bag_rule[1] rules_for_bag[color] = quantity return bags_under_condition, rules_for_bag if __name__ == '__main__': file_reader = FileReader('./input') rules = file_reader.to_str_list() print(rules) print( f"Nombre de sacs possibles 💼 - {count_bags_options('shiny gold', rules)}" ) print( f"Nombre de sacs nécessaires 💼 - {count_required_bags('shiny gold', rules)}" )