DEV Community

Viper
Viper

Posted on • Updated on

Advent of Code 2021 Python Solution: Day 1

Challenge is at this link.
I have made a helper function to read data for all day's problem. Each day's data file will be inside data folder in same directory. The data file will be a text file where contents will be taken from challenge's test example and real input. It will be in the format.

{Test Input}
Split From Here
{Real Input}
Enter fullscreen mode Exit fullscreen mode
def get_data(day=1):
    """
    Returns test and real data in list format.
    Raw data should be maintained as:
        [test data]
        Split From Here
        [actual data]
    """
    file_name = f"data/day{day}.txt"

    with open(file_name) as fp:
        data = fp.read().strip().split("Split From Here")
        data = [d.strip().split("\n") for d in data]
        return data
get_data()
Enter fullscreen mode Exit fullscreen mode

Part 1

data,data1 = get_data() 
data = list(map(int, data))
data1 = list(map(int, data1))

pd = None
res = []
for d in data:
    if pd is None:
        res.append(None)
    else:
        if pd>d:
            res.append("0")
        else:
            res.append("1")
    pd=d
print(res.count("1"))
Enter fullscreen mode Exit fullscreen mode

Answer of test data is 7 and of real input is 1266.

Part 2

w = []
wsum = []
i = 0
ps = None
for j in range(3, len(data1)+1):
    wsum.append(sum(data1[i:j]))
    i+=1

pd = None
res1 = []
for d in wsum:
    if pd is None:
        res1.append(None)
    else:
        if pd>=d:
            res1.append("0")
        else:
            res1.append("1")
    pd=d
print(res1.count("1")
Enter fullscreen mode Exit fullscreen mode

All of my codes are available in GitHub as Jupyter Notebook.

Why not read more?

Top comments (0)