Skip to content

Commit cf8494b

Browse files
Use ruff for Python formatting/linting
1 parent 99f01d7 commit cf8494b

File tree

9 files changed

+90
-163
lines changed

9 files changed

+90
-163
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@ target
2020
*.pyc
2121
__pycache__
2222
.pytest_cache
23+
.ruff_cache

2020/python/aoc_2020/day01.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
from itertools import permutations
33
from operator import mul
44

5-
input = open('2020/input/day01.txt').read()
5+
input = open("2020/input/day01.txt").read()
66
numbers = [int(x) for x in input.splitlines()]
77

8+
89
def find_numbers_with_total_sum(total, n):
910
candidates = permutations(numbers, n)
1011
matches = filter(lambda x: sum(x) == total, candidates)
1112
return next(matches)
1213

13-
print('part one: %d' % reduce(mul, find_numbers_with_total_sum(2020, 2)))
14-
print('part two: %d' % reduce(mul, find_numbers_with_total_sum(2020, 3)))
14+
15+
print("part one: %d" % reduce(mul, find_numbers_with_total_sum(2020, 2)))
16+
print("part two: %d" % reduce(mul, find_numbers_with_total_sum(2020, 3)))

2020/python/aoc_2020/day02.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
11
def parse_line(line):
22
policy, password = line.split(": ")
3-
rule, target = policy.split(' ')
4-
a, b = [int(x) for x in rule.split('-')]
3+
rule, target = policy.split(" ")
4+
a, b = [int(x) for x in rule.split("-")]
55

66
return a, b, target, password
77

8-
input = open('2020/input/day02.txt').read()
8+
9+
input = open("2020/input/day02.txt").read()
910
passwords = [parse_line(x) for x in input.splitlines()]
1011

12+
1113
def validate_part_one(min, max, target, password):
1214
"""
1315
Validate whether the given password contains the target character at least `min` times, and no more than `max`.
1416
"""
1517
count = len([c for c in password if c == target])
1618
return count >= min and count <= max
1719

20+
1821
def validate_part_two(a, b, target, password):
1922
"""
2023
Validate whether the given password contains the target character in position `a` or `b`, but not both.
2124
"""
22-
return (password[a-1] == target) ^ (password[b-1] == target)
25+
return (password[a - 1] == target) ^ (password[b - 1] == target)
26+
2327

24-
print('part one: %d' % len([p for p in passwords if validate_part_one(*p)]))
25-
print('part two: %d' % len([p for p in passwords if validate_part_two(*p)]))
28+
print("part one: %d" % len([p for p in passwords if validate_part_one(*p)]))
29+
print("part two: %d" % len([p for p in passwords if validate_part_two(*p)]))

2020/python/aoc_2020/day03.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from functools import reduce
22
from operator import mul
33

4-
input = open('2020/input/day03.txt').read().splitlines()
4+
input = open("2020/input/day03.txt").read().splitlines()
5+
56

67
def traverse(step_x, step_y):
78
"""
@@ -11,12 +12,18 @@ def traverse(step_x, step_y):
1112

1213
while y < len(input):
1314
line = input[y]
14-
if line[x % len(line)] == '#':
15+
if line[x % len(line)] == "#":
1516
trees += 1
1617
x += step_x
1718
y += step_y
1819

1920
return trees
2021

21-
print('part one: %d' % traverse(3, 1))
22-
print('part two: %d' % reduce(mul, [traverse(*step) for step in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]]))
22+
23+
print("part one: %d" % traverse(3, 1))
24+
print(
25+
"part two: %d"
26+
% reduce(
27+
mul, [traverse(*step) for step in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]]
28+
)
29+
)

2020/python/aoc_2020/day04.py

+24-22
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def __init__(self, fields: Dict[str, str]) -> None:
2121
@property
2222
def has_required_fields(self) -> bool:
2323
"""Checks whether all required fields are present"""
24-
required = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
24+
required = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
2525
for key in required:
2626
if key not in self.fields:
2727
return False
@@ -31,67 +31,69 @@ def has_required_fields(self) -> bool:
3131
@property
3232
def has_valid_fields(self) -> bool:
3333
"""Checks whether the required fields are valid according to the validation rules"""
34-
return (self.has_required_fields and
35-
self.has_valid_birth_year and
36-
self.has_valid_issue_year and
37-
self.has_valid_expiration_year and
38-
self.has_valid_height and
39-
self.has_valid_hair_color and
40-
self.has_valid_eye_color and
41-
self.has_valid_passport_id)
34+
return (
35+
self.has_required_fields
36+
and self.has_valid_birth_year
37+
and self.has_valid_issue_year
38+
and self.has_valid_expiration_year
39+
and self.has_valid_height
40+
and self.has_valid_hair_color
41+
and self.has_valid_eye_color
42+
and self.has_valid_passport_id
43+
)
4244

4345
@property
4446
def has_valid_birth_year(self) -> bool:
4547
"""Birth Year should be at least 1920 and at most 2002"""
46-
return parse_int(self.fields['byr']) in range(1920, 2003)
48+
return parse_int(self.fields["byr"]) in range(1920, 2003)
4749

4850
@property
4951
def has_valid_issue_year(self) -> bool:
5052
"""Issue Year should be at least 2010 and at most 2020"""
51-
return parse_int(self.fields['iyr']) in range(2010, 2021)
53+
return parse_int(self.fields["iyr"]) in range(2010, 2021)
5254

5355
@property
5456
def has_valid_expiration_year(self) -> bool:
5557
"""Expiration Year should be at least 2020 and at most 2030"""
56-
return parse_int(self.fields['eyr']) in range(2020, 2031)
58+
return parse_int(self.fields["eyr"]) in range(2020, 2031)
5759

5860
@property
5961
def has_valid_height(self) -> bool:
6062
"""Height should be at least 150cm and at most 193cm; or at least 59in and at most 76in"""
61-
height = self.fields['hgt']
62-
if height.endswith('cm'):
63-
return parse_int(height.strip('cm')) in range(150, 194)
63+
height = self.fields["hgt"]
64+
if height.endswith("cm"):
65+
return parse_int(height.strip("cm")) in range(150, 194)
6466

65-
if height.endswith('in'):
66-
return parse_int(height.strip('in')) in range(59, 77)
67+
if height.endswith("in"):
68+
return parse_int(height.strip("in")) in range(59, 77)
6769

6870
return False
6971

7072
@property
7173
def has_valid_hair_color(self) -> bool:
7274
"""Hair Color should contain a valid hexadecimal number"""
73-
if re.match('^#[0-9a-f]{6}$', self.fields['hcl']):
75+
if re.match("^#[0-9a-f]{6}$", self.fields["hcl"]):
7476
return True
7577
return False
7678

7779
@property
7880
def has_valid_eye_color(self) -> bool:
7981
"""Eye color should be one of the defined values"""
80-
return self.fields['ecl'] in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']
82+
return self.fields["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
8183

8284
@property
8385
def has_valid_passport_id(self) -> bool:
8486
"""Passport ID should be a nine-digit number, including leading zeroes"""
85-
return len(self.fields['pid']) == 9 and self.fields['pid'].isdigit()
87+
return len(self.fields["pid"]) == 9 and self.fields["pid"].isdigit()
8688

8789

8890
def parse_passport(data: str) -> Passport:
89-
pairs = [pair.split(':') for pair in data.split()]
91+
pairs = [pair.split(":") for pair in data.split()]
9092
fields = dict(pairs)
9193
return Passport(fields)
9294

9395

94-
with open('2020/input/day04.txt', encoding='utf8') as file:
96+
with open("2020/input/day04.txt", encoding="utf8") as file:
9597
passport_data = file.read().split(os.linesep + os.linesep)
9698
passports = [parse_passport(lines) for lines in passport_data]
9799

2020/python/aoc_2020/day05.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ def find_row(seat: str, min_row: int = 0, max_row: int = 127) -> int:
77
"""Recursively finds the row of the given seat."""
88
mid = max_row - int((max_row - min_row) / 2)
99

10-
if seat.startswith('F'):
10+
if seat.startswith("F"):
1111
return find_row(seat[1:], min_row=min_row, max_row=mid)
1212

13-
if seat.startswith('B'):
13+
if seat.startswith("B"):
1414
return find_row(seat[1:], min_row=mid, max_row=max_row)
1515

1616
return min_row
@@ -20,10 +20,10 @@ def find_column(seat: str, min_column: int = 0, max_column: int = 7) -> int:
2020
"""Recursively finds the column of the given seat."""
2121
mid = max_column - int((max_column - min_column) / 2)
2222

23-
if seat.startswith('L'):
23+
if seat.startswith("L"):
2424
return find_column(seat[1:], min_column=min_column, max_column=mid)
2525

26-
if seat.startswith('R'):
26+
if seat.startswith("R"):
2727
return find_column(seat[1:], min_column=mid, max_column=max_column)
2828

2929
return min_column
@@ -34,7 +34,7 @@ def find_seat_location(seat: str) -> Tuple[int, int]:
3434
return find_row(seat[:7]), find_column(seat[7:])
3535

3636

37-
with open('2020/input/day05.txt', encoding='utf8') as file:
37+
with open("2020/input/day05.txt", encoding="utf8") as file:
3838
seats = [find_seat_location(line) for line in file.read().splitlines()]
3939
seat_ids = [row * 8 + column for row, column in seats]
4040
max_seat = max(seat_ids)

2020/python/aoc_2020/day06.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def union(group: List[List[str]]) -> List[str]:
99
for answers in group:
1010
result = set(result) | set(answers)
1111

12-
return result
12+
return list(result)
1313

1414

1515
def intersect(group: List[List[str]]) -> List[str]:
@@ -18,12 +18,13 @@ def intersect(group: List[List[str]]) -> List[str]:
1818
for answers in group:
1919
result = set(result) & set(answers)
2020

21-
return result
21+
return list(result)
2222

2323

24-
with open('2020/input/day06.txt', encoding='utf8') as file:
25-
groups = [group.splitlines()
26-
for group in file.read().split(os.linesep + os.linesep)]
24+
with open("2020/input/day06.txt", encoding="utf8") as file:
25+
groups = [
26+
group.splitlines() for group in file.read().split(os.linesep + os.linesep)
27+
]
2728

2829
print(f"part one: {sum(len(union(group)) for group in groups)}")
2930
print(f"part two: {sum(len(intersect(group)) for group in groups)}")

0 commit comments

Comments
 (0)