<jupyter_start><jupyter_text>Day 3 Part I处理输入，仍然使用Pandas简化代码量，读取输入文件后获得一个Numpy数组，方便后续计算：<jupyter_code>import numpy as np
import pandas as pd

def read_input() -> np.ndarray:
    df = pd.read_csv('input.txt', header=None)
    # 将读取获得的唯一一列字符串打散成每个字符多个列
    df = df[0].apply(lambda x: pd.Series(list(x)))
    # 返回底层Numpy数组
    return df.to_numpy()<jupyter_output><empty_output><jupyter_text>定义一个处理矩阵的函数，因为地图可以无限向右扩展，因此，c每次需要模除矩阵的列数：<jupyter_code>def part1_solution(tree_map: np.ndarray) -> int:
    rows, cols = tree_map.shape
    c = 0
    tree_count = 0
    for r in range(rows):
        c = c % cols
        if tree_map[r, c] == '#':
            tree_count += 1
        c += 3
    return tree_count
tree_map = read_input()
part1_solution(tree_map)<jupyter_output><empty_output><jupyter_text>Part II事实上，第二部分只需要在第一部分上修改即可，为了清晰起见，这里定义了一个新的函数来进行计算：<jupyter_code>from typing import Tuple

def part2_solution(tree_map: np.ndarray, slope: Tuple[int, int]) -> int:
    # 接受一个新的参数，斜率，是一个元组，作为向右前进和向下前进的步长
    rows, cols = tree_map.shape
    c = 0
    tree_count = 0
    for r in range(0, rows, slope[1]):
        c = c % cols
        if tree_map[r, c] == '#':
            tree_count += 1
        c += slope[0]
    return tree_count<jupyter_output><empty_output><jupyter_text>将第一部分结果作为一个简单的测试：<jupyter_code>assert(part2_solution(tree_map, (3, 1)) == 247)<jupyter_output><empty_output><jupyter_text>使用reduce来计算所有斜率会碰到树的乘积：<jupyter_code>from functools import reduce

reduce(lambda x, y: x * y, (part2_solution(tree_map, s) 
                            for s in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]), 1)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12992610837438423, 'fraction_numerical': 0.020320197044334975, 'mean_word_length': 3.9542682926829267, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '154155', 'license': 'Apache-2.0', 'n_tokens_mistral': 798, 'n_tokens_neox': 809, 'n_words': 118, 'path': 'day03/solution.ipynb', 'repo_name': 'wangyingsm/advent-of-code-2020', 'size': '1624'}