def plot_inputs_vs_anomalies(input_index): all_data = get_all_data_results()[0] anomalies_indexes = find_anomalies() input_not_anomalies = [] prediction_not_anomalies = [] input_anomalies = [] prediction_anomalies = [] for i in range(len(all_data)): if i not in anomalies_indexes: input_not_anomalies.append(get_input(i)[input_index]) prediction_not_anomalies.append(all_data[i]) else: input_anomalies.append(get_input(i)[input_index]) prediction_anomalies.append(all_data[i]) plt.figure(input_index) plt.scatter(prediction_not_anomalies, input_not_anomalies, color='blue') plt.scatter(prediction_anomalies, input_anomalies, color='red') # Setup Graph anomaly_legend = mpatches.Patch(color='red', label='Anomaly') normal_legend = mpatches.Patch(color='blue', label='Not Anomaly') plt.legend(handles=[anomaly_legend, normal_legend]) plt.xlabel('Probability that tumor is Benign') plt.ylabel(Y_LABEL[input_index].title()) plt.savefig("Inputs_vs_anomalies_graphs/" + Y_LABEL[input_index].title()) plt.close()
def main(): data = [decode_position(x) for x in get_input(5).split('\n') if x] min_id = min(data) max_id = max(data) for s in range(min_id, max_id): if s not in data: print(s)
def main(): data = [[y for y in x] for x in get_input(11).split('\n') if x] neighbour_lists = [] for row_index, row in enumerate(data): for col_index, col, in enumerate(row): if col == 'L': neighbours = get_neighbours((col_index, row_index), data) neighbour_lists.append(((col_index, row_index), neighbours)) change = True current_layout = [[y for y in x] for x in data] while change: change = False new_layout = [[y for y in x] for x in current_layout] for (col, row), neighbour_set in neighbour_lists: if current_layout[row][col] == 'L': if all( [current_layout[y][x] == 'L' for (x, y) in neighbour_set]): new_layout[row][col] = '#' change = True if current_layout[row][col] == '#': if len([(x, y) for (x, y) in neighbour_set if current_layout[y][x] == '#']) >= 4: new_layout[row][col] = 'L' change = True current_layout = new_layout print(len([x for x in flatten(current_layout) if x == '#']))
def main(): recipes_raw = [x[:-1].split(' (contains ', 1) for x in get_input(21).split('\n') if x] recipes = [] all_allergens = set() for ingredients, allergens in recipes_raw: ingredients = ingredients.split(' ') allergens = allergens.split(', ') recipes.append([ingredients, allergens]) for a in allergens: all_allergens.add(a) possible_ingredients = [] for a in all_allergens: ingredients_with_allergen = [ingredients for ingredients, allergens in recipes if a in allergens] possible_ingredients.append([a, list(set.intersection(*map(set, ingredients_with_allergen)))]) allergens_mapping = {} while True: tmp = [] for key, value in possible_ingredients: used_ingredients = [a_value for a_value in allergens_mapping.values()] ing_list = [x for x in value if x not in used_ingredients] if len(ing_list) == 1: allergens_mapping[key] = ing_list[0] else: tmp.append([key, value]) possible_ingredients = tmp if len(possible_ingredients) == 0: break print(sum([len([x for x in ingredients if x not in allergens_mapping.values()]) for ingredients, allergens in recipes]))
def main(): data = sorted([int(x) for x in get_input(10).split('\n') if x]) max_val = max(data) diffs = [] prev = 0 data.append(max_val + 3) for d in data: diffs.append(d - prev) prev = d # Looks like the difference is always 1 or 3. So we can ignore any logic for steps of 2. # Since the gap of 3 is required we can split on those and calculate those separately. # The longest such series is 4 in my input. # 1, 0|12|5 = 1 # 2, 0|123|6 = 2 [123, 13] # 3, 0|1234|7 = 4 [1234, 124, 134, 14] # 4, 0|12345|8 = 7 [12345, 1245, 125, 1235, 135, 1345, 145] parts = [len(y) for y in (''.join([str(x) for x in diffs])).split('3') if y and len(y) > 1] value = 1 for p in parts: if p == 2: value = value * 2 elif p == 3: value = value * 4 elif p == 4: value = value * 7 print(value)
def main(): data = [int(x) for x in get_input(15).split('\n')[0].split(',')] last_position = {} for i, x in enumerate(data): last_position[x] = i keys = set(data[:-1]) prev = data[-1] prev_index = 0 i = len(data) while True: curr = prev if prev in keys: y = i - prev_index - 1 prev_index = last_position[y] if y in last_position else 0 last_position[y] = i prev = y else: prev_index = last_position[0] last_position[0] = i prev = 0 keys.add(curr) if i == 30000000: print(curr) break i += 1
def main(): data = [ dict([y.split(':') for y in x.replace('\n', ' ').split(' ')]) for x in get_input(4).split('\n\n') if x ] print( len([x for x in data if has_required_fields(x) and has_valid_data(x)]))
def main(): data = [(x[0], int(x[1:])) for x in get_input(12).split('\n') if x] north = 0 east = 0 waypoint_north = 1 waypoint_east = 10 for d, l in data: if d == 'F': north += waypoint_north * l east += waypoint_east * l if d == 'L': d = 'R' l = 360 - l if d == 'N': waypoint_north += l elif d == 'S': waypoint_north -= l elif d == 'E': waypoint_east += l elif d == 'W': waypoint_east -= l elif d == 'R': for r in range(int(l / 90)): tmp = waypoint_north waypoint_north = -waypoint_east waypoint_east = tmp print(abs(north) + abs(east))
def main(): rules, messages = get_input(19).split('\n\n', 1) raw_rules = dict( [x.split(':') for x in rules.replace('"', '').split('\n') if x]) rules = {} for rule_nr, rule in raw_rules.items(): rule = f'{rule} ' parts = rule.split('|') rule = ' | '.join([f' ( {x} ) ' for x in parts]) rules[rule_nr] = f' ( {rule} ) '.replace(' ', ' ') rule_0 = parse_rule('0', rules) # 8: 42 | 42 8 # 11: 42 31 | 42 11 31 rule_42 = parse_rule('42', rules) rule_31 = parse_rule('31', rules) rule_0 = rule_0.replace('eight', f'({rule_42})+') rule_0 = rule_0.replace( 'eleven', f'(' f'(({rule_42})({rule_31}))|' f'(({rule_42})({rule_42})({rule_31})({rule_31}))|' f'(({rule_42})({rule_42})({rule_42})({rule_31})({rule_31})({rule_31}))|' f'(({rule_42})({rule_42})({rule_42})({rule_42})({rule_31})({rule_31})({rule_31})({rule_31}))' f')') messages = [x for x in messages.split('\n') if x] matches = 0 for message in messages: if re.match(f"^{rule_0.replace(' ', '')}$", message): matches += 1 print(matches)
def main(): original_instructions = [x.split(' ') for x in get_input(8).split('\n') if x] for index, instruction in enumerate(original_instructions): instructions = [(x[0], x[1]) for x in original_instructions] run = False if instruction[0] == 'nop': instructions[index] = ('jmp', instructions[index][1]) run = True elif instruction[0] == 'jmp': instructions[index] = ('nop', instructions[index][1]) run = True executed_instructions = [] acc = 0 counter = 0 if run: while True: if counter == len(instructions): print(acc) return inst, value = instructions[counter] if counter in executed_instructions: break executed_instructions.append(counter) if inst == 'nop': counter += 1 elif inst == 'acc': counter += 1 acc += int(value) elif inst == 'jmp': counter += int(value)
def main(): rules, messages = get_input(19).split('\n\n', 1) raw_rules = dict( [x.split(':') for x in rules.replace('"', '').split('\n') if x]) rules = {} for rule_nr, rule in raw_rules.items(): rule = f'{rule} ' parts = rule.split('|') rule = ' | '.join([f' ( {x} ) ' for x in parts]) rules[rule_nr] = f' ( {rule} ) '.replace(' ', ' ') tmp = rules['0'] while any(x in rules for x in tmp.split(' ')): parts = tmp.split(' ') rule = '' for part in parts: if part in rules: rule = f'{rule} {rules[part]}' else: rule = f'{rule} {part}' tmp = rule rules['0'] = tmp messages = [x for x in messages.split('\n') if x] matches = 0 for message in messages: if re.match(f"^{rules['0'].replace(' ', '')}$", message): matches += 1 print(matches)
def main(): cups = [int(x) for x in get_input(23).split('\n')[0]] for x in range(max(cups) + 1, 1000000 + 1): cups.append(x) first = cups[0] prev = None cup_dict = {} for cup in cups: tmp = Item(cup) cup_dict[cup] = tmp if prev: prev.next = tmp prev = tmp prev.next = cup_dict[first] current = cup_dict[first] for x in range(10000000): picked = [current.next, current.next.next, current.next.next.next] picked_nrs = [x.value for x in picked] current.next = picked[2].next picked[2].next = None i = -1 while current.value + i in picked_nrs or current.value + i < 1: if current.value + i < 1: i += 1000000 else: i -= 1 tmp = cup_dict[current.value + i] tmp_next = tmp.next tmp.next = picked[0] picked[2].next = tmp_next current = current.next if x % 100000 == 0: print(f'\r{x/100000}%', end='') print() print(cup_dict[1].next.value * cup_dict[1].next.next.value)
def main(): data = [int(x) for x in get_input(1).split('\n') if x] for d in data: for e in data: if e == d: continue if 2020 - d - e in data: print(d, e, 2020 - d - e, d * e * (2020 - d - e)) return
def main(): input_data = get_input(18) data = [x for x in input_data.split('\n') if x] # for eq in data: # print(eq) # ans = solve(eq.replace(' ', '')) # print('=', ans) response = sum([solve(eq) for eq in data]) print(response)
def main(): data = [x.split(': ') for x in get_input(2).split('\n') if x] count = 0 for policy, password in data: min_max, letter = policy.split(' ', 1) min_nr, max_nr = [int(x) for x in min_max.split('-')] if bool(password[min_nr - 1] == letter) ^ bool(password[max_nr - 1] == letter): count += 1 print(count)
def main(): data = sorted([int(x) for x in get_input(10).split('\n') if x]) max_val = max(data) diffs = [] prev = 0 data.append(max_val + 3) for d in data: diffs.append(d - prev) prev = d print(diffs.count(1) * diffs.count(3))
def main(): data = [x.split(': ') for x in get_input(2).split('\n') if x] count = 0 for policy, password in data: min_max, letter = policy.split(' ', 1) min_nr, max_nr = [int(x) for x in min_max.split('-')] nr_of_chosen_letter = len(password) - len(password.replace(letter, '')) if min_nr <= nr_of_chosen_letter <= max_nr: count += 1 print(count)
def main(): data = [x for x in get_input(3).split('\n') if x] slope = 3 count = 0 for nr, row in enumerate(data): while (nr * slope) >= len(row): row += row if row[nr * slope] == '#': count += 1 print(count)
def main(): data = [format_row(x) for x in get_input(24).split('\n')] positions = [] for d in data: pos = get_position(d) if pos in positions: positions.remove(pos) else: positions.append(pos) print(len(positions)) assert len(positions) > 201
def main(): data = [x.split(' bags contain ') for x in get_input(7).split('\n') if x] bags = {} for bag in data: bags[bag[0]] = [ x.split(' ', 1) for x in bag[1].replace('.', '').replace( ' bags', '').replace(' bag', '').split(', ') if x != 'no other' ] current_color = 'shiny gold' print(calc_bags_in_bags(current_color, bags) - 1)
def main(): data = [x for x in get_input(3).split('\n') if x] slopes = [0.5, 1, 3, 5, 7] counts = [0, 0, 0, 0, 0] for nr, row in enumerate(data): while (nr * max(slopes)) >= len(row): row += row for slope_index, slope in enumerate(slopes): if (nr * slope) == int(nr * slope): if row[int(nr * slope)] == '#': counts[slope_index] += 1 print(reduce(lambda x, y: x * y, counts))
def export_anomalies(): anomalies = find_anomalies() with open('anomalies.csv', 'w') as csvfile: fieldnames = [ 'id', 'mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness', 'mean compactness', 'mean concavity', 'mean concave points', 'mean symmetry', 'mean fractal dimension', 'radius error', 'texture error', 'perimeter error', 'area error', 'smoothness error', 'compactness error', 'concavity error', 'concave points error', 'symmetry error', 'fractal dimension error', 'worst radius', 'worst texture', 'worst perimeter', 'worst area', 'worst smoothness', 'worst compactness', 'worst concavity', 'worst concave points', 'worst symmetry', 'worst fractal dimension' ] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in anomalies: anomaly_input = get_input(i) writer.writerow({ 'id': i, 'mean radius': anomaly_input[0], 'mean texture': anomaly_input[1], 'mean perimeter': anomaly_input[2], 'mean area': anomaly_input[3], 'mean smoothness': anomaly_input[4], 'mean compactness': anomaly_input[5], 'mean concavity': anomaly_input[6], 'mean concave points': anomaly_input[7], 'mean symmetry': anomaly_input[8], 'mean fractal dimension': anomaly_input[9], 'radius error': anomaly_input[10], 'texture error': anomaly_input[11], 'perimeter error': anomaly_input[12], 'area error': anomaly_input[13], 'smoothness error': anomaly_input[14], 'compactness error': anomaly_input[15], 'concavity error': anomaly_input[16], 'concave points error': anomaly_input[17], 'symmetry error': anomaly_input[18], 'fractal dimension error': anomaly_input[19], 'worst radius': anomaly_input[20], 'worst texture': anomaly_input[21], 'worst perimeter': anomaly_input[22], 'worst area': anomaly_input[23], 'worst smoothness': anomaly_input[24], 'worst compactness': anomaly_input[25], 'worst concavity': anomaly_input[26], 'worst concave points': anomaly_input[27], 'worst symmetry': anomaly_input[28], 'worst fractal dimension': anomaly_input[29] })
def main(): data_set, n_neurons, iterations, k, plot_k, neighborhood, learning_rate\ , radius = get_input() cities = read_data(data_set) scaling, cities = normalize(cities) neuron_count = len(cities) * n_neurons neurons = init_neurons(neuron_count) # TODO maybe distance param? som(neurons, cities, iterations, k, plot_k, neighborhood, learning_rate, radius, scaling)
def main(): data = [format_row(x) for x in get_input(24).split('\n')] black_tiles = [] for d in data: pos = get_position(d) if pos in black_tiles: black_tiles.remove(pos) else: black_tiles.append(pos) for x in range(100): new_black = get_new_positions(black_tiles) print(len(new_black)) black_tiles = new_black
def main(): player_1, player_2 = [[int(y) for y in x.split('\n')[1:]] for x in get_input(22).split('\n\n') if x] while len(player_1) > 0 and len(player_2) > 0: card_1 = player_1.pop(0) card_2 = player_2.pop(0) if card_1 > card_2: player_1.append(card_1) player_1.append(card_2) else: player_2.append(card_2) player_2.append(card_1) res = player_1 + player_2 print(sum([x * (len(res) - i) for i, x in enumerate(res)]))
def main(): data = [int(x) for x in get_input(15).split('\n')[0].split(',')] i = len(data) while True: prev = data[i - 1] prev_list = data[:-1] if prev in prev_list: data.append(1 + prev_list[::-1].index(prev)) else: data.append(0) if len(data) == 2020: print(data[-1]) break i += 1
def main(): tiles = [Tile(tile) for tile in get_input(20).split('\n\n') if tile] mult = 1 for i, tile in enumerate(tiles): possible_neighbours = [] for tile2 in tiles: if tile == tile2: continue possible_sides = tile.nr_of_sides_that_can_be_neighbouring(tile2) if possible_sides: possible_neighbours.append(tile2) if len(possible_neighbours) == 2: mult *= tile.nr print(mult)
def main(): instructions = [x.split(' ') for x in get_input(8).split('\n') if x] executed_instructions = [] acc = 0 counter = 0 while True: inst, value = instructions[counter] if counter in executed_instructions: print(acc) break executed_instructions.append(counter) if inst == 'nop': counter += 1 elif inst == 'acc': counter += 1 acc += int(value) elif inst == 'jmp': counter += int(value)
def main(): data = [x for x in get_input(13).split('\n') if x] busses = [(-i, int(x)) for i, x in enumerate(data[1].split(',')) if x != 'x'] # Using something called Chinese Remainder Theorem m = 1 for reminder, x in busses: m *= x total = 0 for rem, x in busses: div = int(m / x) tmp = div % x j = 0 while (tmp * j) % x != 1: j += 1 total += rem * div * j print(total % m)
def main(): public_keys = [int(x) for x in get_input(25).split('\n') if x] subject_nr = 7 i = 0 loop_nrs = {} tmp = 1 while len(public_keys) != len(loop_nrs.keys()): tmp = (tmp * subject_nr) % 20201227 if tmp in public_keys: loop_nrs[tmp] = i i += 1 loop_nr_list = [loop_nrs[pk] for pk in public_keys] print(loop_nrs) loop_nr = loop_nr_list[0] subject_nr = public_keys[1] print(loop_nr, subject_nr) tmp = 1 for _ in range(loop_nr + 1): tmp = (tmp * subject_nr) % 20201227 print(tmp)