コード例 #1
0
def test_rename_col(object):
    """
    Test the rename_col function in cleaning.py (FF_wave class)
    """
    print("Testing rename_col")
    assert_equals(['a', 'b', 'c', 'd', 'e', 'f'],
                  object.rename_col(['a', 'b', 'c', 'd', 'e', 'f']).columns)
コード例 #2
0
def test_challenge12():

	if not detectECB(encryption_oracle):
		return False
	block_size = findBlockSize(encryption_oracle)
	print("Block size:", block_size)
	res = findAll(encryption_oracle)
	print("RESULT", res)
	assert_equals(res, appText, 'Challenge 12 decryption')
コード例 #3
0
ファイル: c14.py プロジェクト: vassilisp/matasano_cryptopals
def test_challenge14():

	ow = OracleWrapper(encryption_oracle)
	woracle = ow.getOracle()

	if not detectECB(woracle):
		return False
	blockSize = findBlockSize(woracle)
	print("Block size:", blockSize)

	res = findAll(woracle)
	print("RESULT", res)
	assert_equals(res, appText, 'Challenge 14 decryption')
コード例 #4
0
def test_challenge2_xor():
	res1 = fixed_xor(bin_input1, bin_input2)
	res1 = binascii.hexlify(res1).decode()
	assert_equals(res1, expected, 'xor1')
コード例 #5
0
            r -= 1
            q += 1
        elif step == "se":
            q += 1
            s -= 1
        elif step == "sw":
            q -= 1
            r += 1
        elif step == "nw":
            q -= 1
            s += 1
    return int((abs(q) + abs(r) + abs(s)) / 2)


for path, distance in examples.items():
    u.assert_equals(get_distance_from_path(path), distance)

u.answer_part_1(get_distance_from_path(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def get_further_during_path(path):
    q, r, s = 0, 0, 0
    further = 0
    for step in path.split(","):
        if step == "n":
            s += 1
            r -= 1
        elif step == "s":
            r += 1
コード例 #6
0
def test_gender_response(object):
    """
    Test the gender_response function in cleaning.py (FF_wave class)
    """
    print("Testing gender_response")
    assert_equals(1, object.gender_response().loc[1, 'gender'])
コード例 #7
0
def test_sum_subscale(object):
    """
    Test the sum_subscale function in cleaning.py (FF_wave class)
    """
    print("Testing sum_subscale")
    assert_equals(2.0, object.sum_subscale('del', 1).loc[2, 'del_sum'])
コード例 #8
0
        while len(re.findall(redObjects, s)) > 0:
            print(f"remove {len(re.findall(redObjects, s))} red objects")
            s = re.sub(redObjects, "> 0 <", s)
        print(
            f"factorize {len(re.findall(objectsWithoutChildren, s))} non red objects"
        )
        s = re.sub(objectsWithoutChildren,
                   lambda x: f"> {sumOfAllNumbers(x.group(0))} <", s)
        print("--------")

    # print(string)
    return s


# [1,2,3] and {"a":2,"b":4} both have a sum of 6
u.assert_equals(sumOfAllNumbers("[1,2,3]"), 6)
u.assert_equals(sumOfAllNumbers('{"a":2,"b":4}'), 6)

# [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
u.assert_equals(sumOfAllNumbers("[[[3]]]"), 3)
u.assert_equals(sumOfAllNumbers('{"a":{"b":4},"c":-1}'), 3)

# {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
u.assert_equals(sumOfAllNumbers('{"a":[-1,1]}'), 0)
u.assert_equals(sumOfAllNumbers('[-1,{"a":1}]'), 0)

# [] and {} both have a sum of 0.
u.assert_equals(sumOfAllNumbers("[]"), 0)
u.assert_equals(sumOfAllNumbers(r"{}"), 0)

u.answer_part_1(sumOfAllNumbers(inputStr))
コード例 #9
0
        while destination in picked or destination < mini:
            destination -= 1
            if destination < mini:
                destination = maxi
        # THIS is slow: searching a value in a deque
        destination_index = cups.index(destination) + 1
        for add in reversed(picked):
            cups.insert(destination_index, add)
        # The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
        cups.rotate(-1)  # this places the new current cup at the beginning of the deque
    return cups


example_cups = deque(map(int, list(example_labeling)))
example_cups = crab_moves_cups(example_cups)
u.assert_equals("".join(map(str, example_cups)), "837419265")


my_cups = deque(map(int, list(my_labeling)))
cups_after_100_moves = crab_moves_cups(my_cups, 100)
index_of_one = cups_after_100_moves.index(1)
cups_after_100_moves.rotate(-index_of_one)  # put 1 at the beginning of the deque
cups_after_100_moves.popleft()  # remove the one
answer_part_1 = "".join(map(str, cups_after_100_moves))

u.assert_equals(answer_part_1, "25368479")
u.answer_part_1(answer_part_1)

# # part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_

コード例 #10
0
def look_for_ten_recipes_after_nth(n: int):
    score = deque([3, 7])
    elves_position = [0, 1]
    # debug_position(score, elves_position)
    while True:
        new_scores = sum(score[pos] for pos in elves_position)
        score.extend(map(int, list(str(new_scores))))
        elves_position = [(pos + score[pos] + 1) % len(score)
                          for pos in elves_position]
        # debug_position(score, elves_position)
        if len(score) >= n + 10:
            break
    return "".join(map(str, (score[x] for x in range(n, n + 10))))


u.assert_equals(look_for_ten_recipes_after_nth(9), "5158916779")
u.assert_equals(look_for_ten_recipes_after_nth(5), "0124515891")
u.assert_equals(look_for_ten_recipes_after_nth(2018), "5941429882")
u.assert_equals(look_for_ten_recipes_after_nth(18), "9251071085")

u.answer_part_1(look_for_ten_recipes_after_nth(int(puzzle_input)))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def look_for_pattern_in_recipes(pattern: str):
    score = "37"
    elves_position = [0, 1]
    init = time()
    for i in count():
        if i % 10000 == 0:
コード例 #11
0
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm

iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929

hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm

hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
"""

u.assert_equals(count_valid_passports_in_batch(example_batch), 2)

u.answer_part_1(count_valid_passports_in_batch(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_

# criteria which are easily regexable:
EASY_CRITERIA = tuple(
    map(
        lambda p: re.compile(p, re.M),
        (
            # hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
            # do the elves really define their hair color using hexcodes??
            r"hcl:#[0-9a-f]{6}\s",
            # ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
            r"ecl:(amb|blu|brn|gry|grn|hzl|oth)\s",
コード例 #12
0
# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def get_power_consumption(raw_input):
    rows = raw_input.splitlines()
    first_row = rows[0]
    width = len(first_row)
    length = len(rows)
    gamma_string = "".join(
        "0" if [r[bit] for r in rows].count("0") > length / 2 else "1"
        for bit in range(width))
    epsilon_string = "".join("0" if c == "1" else "1" for c in gamma_string)
    return int(gamma_string, 2) * int(epsilon_string, 2)


u.assert_equals(get_power_consumption(raw_example), 198)
u.answer_part_1(get_power_consumption(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def get_life_support_rating(raw_input):
    rows = raw_input.splitlines()
    first_row = rows[0]
    width = len(first_row)
    length = len(rows)
    oxygen = rows.copy()
    co2 = rows.copy()
    for bit in range(width):
        o2_sum = sum(int(r[bit]) for r in oxygen)
        o2_criteria = str(int(o2_sum >= len(oxygen) / 2))
コード例 #13
0
import utils as u
from operator import xor
from functools import reduce

with open(__file__ + ".input.txt", "r+") as file:
    raw_input = file.read()

# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def rotate(l, steps):
    steps = steps % len(l)
    return l[steps:] + l[:steps]


u.assert_equals(rotate(list(range(5)), 2), [2, 3, 4, 0, 1])
u.assert_equals(rotate(list(range(5)), 7), [2, 3, 4, 0, 1])
u.assert_equals(rotate(list(range(5)), 5), list(range(5)))


def apply_lengths(list, lengths):
    total_rotation = 0
    for skip, length in enumerate(lengths):
        if length == len(list):
            list = list[::-1]
        elif length <= 1:
            list = list
        else:
            list = list[length - 1::-1] + list[length:]
        list = rotate(list, skip + length)
        total_rotation += skip + length
コード例 #14
0
    (17, 18, 1),
    # cross 4-5-19
    (4, 5, 2),
    (5, 19, 2),
    (4, 19, 2),
    # branch D : 19-20-21-22
    (19, 20, 1),
    (20, 21, 1),
    (21, 22, 1),
    # right : 5-6
    (5, 6, 1),
)
for n1, n2, w in distances_edges:
    distances.add_edge(n1, n2, weight=w)

u.assert_equals(nx.shortest_path_length(distances, 8, 6, weight="weight"), 10)
u.assert_equals(nx.shortest_path_length(distances, 6, 10, weight="weight"), 10)


COSTS = {
    "A": 1,
    "B": 10,
    "C": 100,
    "D": 1000,
}

HALLWAY = tuple(range(7))

ROOMS_BY_LETTER = {
    "A": (7, 8, 9, 10),
    "B": (11, 12, 13, 14),
コード例 #15
0
def test_challenge2_xor3():
	res3 = fixed_xor3(bin_input1, bin_input2)
	res3 = binascii.hexlify(res3).decode()
	assert_equals(res3, expected, 'xor3')
コード例 #16
0
def test_challenge2_xor2():
	res2 = fixed_xor2(bin_input1, bin_input2)
	res2 = binascii.hexlify(res2).decode()
	assert_equals(res2, expected, 'xor2')
コード例 #17
0
def count_active_neighbors(grid, *coordinates):
    x, y, z = coordinates
    return -grid[x, y, z] + sum(grid[xn, yn, zn] for xn in range(x - 1, x + 2)
                                for yn in range(y - 1, y + 2)
                                for zn in range(z - 1, z + 2))


def boot_grid_for_6_cycles(raw_input):
    grid = build_grid_from_input(raw_input)
    for i in range(6):
        grid = build_new_grid(grid)
    return sum(grid.values())


u.assert_equals(boot_grid_for_6_cycles(example_input), 112)

u.answer_part_1(boot_grid_for_6_cycles(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_

# Basically the same as part 1, with 4 dimensions:
# I copy-pasted and added "hyper" in function names.


def build_hyper_grid_from_input(input):
    rows = input.strip().splitlines()
    grid = defaultdict(
        int)  # grid[something] will be 0 if <something> is not defined
    for y, row in enumerate(rows):
        for x, char in enumerate(row):
コード例 #18
0
    depth = 0
    for row in raw_input.splitlines():
        value = int(row[-1:])
        dir = row[0]
        if dir == "f":
            x += value
        elif dir == "u":
            depth -= value
            if depth < 0:
                print("uh oh, flying submarine??")
        elif dir == "d":
            depth += value
    return x * depth


u.assert_equals(find_where_its_going(raw_example), 150)
u.answer_part_1(find_where_its_going(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def calculate_with_aim(raw_input):
    x = 0
    depth = 0
    aim = 0
    for row in raw_input.splitlines():
        value = int(row[-1:])
        dir = row[0]
        if dir == "f":
            x += value
            depth += value * aim
コード例 #19
0
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce"""

# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def count_easy_letters_in_output(raw_input):
    outputs = [row.split(" | ")[1] for row in raw_input.splitlines()]
    outputs = tuple(itertools.chain(*(r.split() for r in outputs)))
    return len(tuple(filter(lambda x: len(x) in (2, 4, 3, 7), outputs)))


u.assert_equals(count_easy_letters_in_output(example_input), 26)
u.answer_part_1(count_easy_letters_in_output(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def output_sequence_from_entry(entry):
    all_sequences = tuple("".join(sorted(x))
                          for x in entry.split(" | ")[0].split(" "))
    outputs = tuple("".join(sorted(x))
                    for x in entry.split(" | ")[1].split(" "))

    one = next(x for x in all_sequences if len(x) == 2)
    four = next(x for x in all_sequences if len(x) == 4)
    seven = next(x for x in all_sequences if len(x) == 3)
    eight = next(x for x in all_sequences if len(x) == 7)
コード例 #20
0
    return valid_values


def compute_scanning_error_rate(raw_notes, valid_values):
    rows = raw_notes.splitlines()
    nearby_tickets_row = rows.index("nearby tickets:")
    invalid_values = []
    for raw_ticket in rows[nearby_tickets_row + 1:]:
        invalid_values.extend(value
                              for value in map(int, raw_ticket.split(","))
                              if value not in valid_values)
    return sum(invalid_values)


valid_values = extract_valid_values_from_raw_input(example_input)
u.assert_equals(compute_scanning_error_rate(example_input, valid_values), 71)

my_valid_values = extract_valid_values_from_raw_input(raw_input)
u.answer_part_1(compute_scanning_error_rate(raw_input, my_valid_values))
# 16908 too low: i will try use a list instead of a set

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def extract_valid_tickets(raw_notes, valid_values):
    rows = raw_notes.splitlines()
    nearby_tickets_row = rows.index("nearby tickets:")
    for raw_ticket in rows[nearby_tickets_row + 1:]:
        int_ticket = tuple(map(int, raw_ticket.split(",")))
        if all(value in valid_values for value in int_ticket):
            yield (int_ticket)
コード例 #21
0
        after_east_moves.append(new_row)
    after_south_moves = [[] for _ in range(len(current_step))]
    for col in range(len(current_step[0])):
        col_string = "".join(row[col] for row in after_east_moves)
        col_string = col_string.replace("v.", ".v")
        column = list(col_string)
        if after_east_moves[-1][col] == "v" and after_east_moves[0][col] == ".":
            column[0] = "v"
            column[-1] = "."
            changed = True
        for row, element in enumerate(column):
            after_south_moves[row].append(element)
    if not changed:
        changed = current_step != after_south_moves
    return after_south_moves, changed


def part_1(raw_input):
    state = [list(row) for row in raw_input.splitlines()]
    changed = True
    done_steps = 0
    while changed:
        state, changed = get_next_step(state)
        done_steps += 1
    return done_steps


u.assert_equals(part_1(example), 58)
u.answer_part_1(part_1(raw_input))
# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
コード例 #22
0
    reg = re.compile(
        r"([a-z]+) (inc|dec) (-?\d+) if ([a-z]+) ([<>=!]+) (-?\d+)")
    registries = defaultdict(lambda: 0)
    for row in raw_input.splitlines():
        m = reg.match(row)
        groups = m.groups()
        if interpret_condition(groups[3:], registries):
            registry, action, value = groups[:3]
            if action == "dec":
                registries[registry] -= int(value)
            elif action == "inc":
                registries[registry] += int(value)
    return max(registries.values())


u.assert_equals(interpret_instructions(example), 1)
u.answer_part_1(interpret_instructions(raw_input))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def interpret_instructions_part_2(raw_input):
    reg = re.compile(
        r"([a-z]+) (inc|dec) (-?\d+) if ([a-z]+) ([<>=!]+) (-?\d+)")
    registries = defaultdict(lambda: 0)
    max_ever = 0
    for row in raw_input.splitlines():
        m = reg.match(row)
        groups = m.groups()
        if interpret_condition(groups[3:], registries):
            registry, action, value = groups[:3]
コード例 #23
0
SUBJECT = 7

# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def find_loop_size(public_key: int):
    value = 1
    for loop_size in itertools.count(start=1):
        value = (value * SUBJECT) % MODULO
        if value == public_key:
            return loop_size


def find_encryption_key(public_key: int, loop_size_of_other_device: int):
    return pow(public_key, loop_size_of_other_device, MODULO)


u.assert_equals(find_loop_size(5764801), 8)
u.assert_equals(find_loop_size(17807724), 11)

u.assert_equals(find_encryption_key(5764801, 11), 14897079)

card_loop_size = find_loop_size(card_key)
u.pink(f"card loop: {card_loop_size}")
encryption_key = find_encryption_key(door_key, card_loop_size)

u.answer_part_1(encryption_key)
# 1018011 too low

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
コード例 #24
0
        for yrange in yranges:
            for zrange in zranges:
                if (*xrange, *yrange, *zrange) == b:
                    continue
                yield (*xrange, *yrange, *zrange)


def volume(cuboid):
    if cuboid is None:
        return 0
    x1, x2, y1, y2, z1, z2 = cuboid
    return (1 + x2 - x1) * (1 + y2 - y1) * (1 + z2 - z1)


cuboid = (0, 99, 0, 99, 0, 0)
u.assert_equals(volume(cuboid), 10000)
sub = (0, 9, 0, 9, 0, 0)
u.assert_equals(volume(sub), 100)
for c in divide_a_around_b(cuboid, sub):
    print(c)
    print(volume(c))
u.assert_equals(sum(volume(c) for c in divide_a_around_b(cuboid, sub)), 10000 - 100)


def part_2(raw_input):
    regex = re.compile(
        r"(?:off|on) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)"
    )
    on_cuboids = list()
    rows = raw_input.splitlines()
    for row in rows:
コード例 #25
0
def test_replacement(object):
    """
    Test the replacement function in cleaning.py (FF_wave class)
    """
    print("Testing replacement")
    assert_equals(2, object.replacement('f', 1, 2).loc[3, 'f'])
コード例 #26
0
# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def bits_from_integer(integer):
    bits = list(bin(integer)[2:])
    bits = ["0"] * (36 - len(bits)) + bits
    return list(reversed(bits))


def bits_to_integer(bits):
    bits = list(reversed(bits))
    return int("".join(bits), 2)


u.assert_equals(bits_to_integer(bits_from_integer(25)), 25,
                "bits_from/to_integer")

u.assert_equals(bits_to_integer(bits_from_integer(2**36)), 2**36,
                "bits_from/to_integer")


def parse_input_to_program(raw_input):
    memory = defaultdict(lambda: 0)
    for line in raw_input.splitlines():
        if line.startswith("mask"):
            mask = line[7:]
        elif line.startswith("mem"):
            address, value = tuple(
                map(int,
                    re.findall(MEMORY_INSTRUCTION, line)[0]))
            bits = bits_from_integer(value)
コード例 #27
0
def test_avg_subscale(object):
    """
    Test the avg_subscale function in cleaning.py (FF_wave class)
    """
    print("Testing avg_subscale")
    assert_equals(4.0, object.avg_subscale('f', 'agg', 1).loc[1, 'f_agg_avg'])
コード例 #28
0
def get_place_coordinates(boarding_pass):
    row_instructions = boarding_pass[:-3]
    col_instructions = boarding_pass[-3:]
    # hey you know what, it's a binary number where B = 1 and F = 0
    row_binary = row_instructions.replace("F", "0").replace("B", "1")
    # or where R = 1 and L = 0
    col_binary = col_instructions.replace("L", "0").replace("R", "1")
    return (int(row_binary, base=2), int(col_binary, base=2))


def get_place_id(row, col):
    return 8 * row + col


u.assert_equals(get_place_coordinates("BFFFBBFRRR"), (70, 7))
u.assert_equals(get_place_coordinates("FFFBBBFRRR"), (14, 7))
u.assert_equals(get_place_coordinates("BBFFBBFRLL"), (102, 4))

u.assert_equals(get_place_id(70, 7), 567)
u.assert_equals(get_place_id(14, 7), 119)
u.assert_equals(get_place_id(102, 4), 820)

place_ids = [
    get_place_id(*get_place_coordinates(boarding_pass))
    for boarding_pass in raw_input.splitlines()
]

u.answer_part_1(max(place_ids))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
コード例 #29
0
                col += 1
            elif direction == "ne":
                row -= 1
                col += 1
            else:
                print("duh?")
        tiling[row, col] *= -1
    return tiling


def count_black_tiles(grid: dict):
    return list(grid.values()).count(-1)


example_tiling = extract_black_tiles(example)
u.assert_equals(count_black_tiles(example_tiling), 10)

tiling = extract_black_tiles(raw_input)
u.assert_equals(count_black_tiles(tiling), 317)

u.answer_part_1(count_black_tiles(tiling))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_


def count_black_neighbors(grid: defaultdict, coordinates: tuple):
    return [
        grid[coordinates] for coordinates in get_neighbors_coordinates(coordinates)
    ].count(-1)

コード例 #30
0

def find_corner_tiles(raw_tileset):
    contacts = build_contact_graph(raw_tileset)
    # in contacts graph:
    # - insider tiles have 4 neighbors
    # - border tiles have 3 neighbors
    # - corner tiles have 2 neighbors
    return [
        node
        for node in contacts.nodes()
        if len(list(nx.neighbors(contacts, node))) == 2
    ]


u.assert_equals(prod(find_corner_tiles(example_input)), 20899048083289)
u.answer_part_1(prod(find_corner_tiles(raw_input)))

# part 2 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_

TOP = 0
RIGHT = 1
BOTTOM = 2
LEFT = 3

DIRECTIONS = ("Top", "Right", "Bottom", "Left")


SEA_MONSTER = """
                  _ 
*    __    __    ^^>