Refactoring

This commit is contained in:
2026-06-23 17:47:18 +02:00
parent 4681a782b5
commit 2e64eef9a2

View File

@@ -25,44 +25,32 @@
# How many strings are nice?
from collections import Counter
with open("files/P5.txt") as f:
strings = [line for line in f.read().strip().split()]
VOWELS = set("aeiou")
FORBIDDEN = ("ab", "cd", "pq", "xy")
def has_enough_vowels(s: str) -> bool:
num_vowels = sum(s.lower().count(v) for v in "aeiou")
if num_vowels >= 3:
return True
return False
return sum(char in VOWELS for char in s) >= 3
def has_double_letter(s: str) -> bool:
double_letters = sum(1 for i, j in zip(s, s[1:]) if i == j)
if double_letters >= 1:
return True
return False
return any(left == right for left, right in zip(s, s[1:]))
def has_substring(s: str) -> bool:
substrings = ["ab", "cd", "pq", "xy"]
for substring in substrings:
if substring in s:
return True
return False
return any(substring in s for substring in FORBIDDEN)
def part_1() -> None:
nice = 0
for string in strings:
if (
has_enough_vowels(string)
and has_double_letter(string)
and not has_substring(string)
):
nice += 1
nice = sum(
has_enough_vowels(string)
and has_double_letter(string)
and not has_substring(string)
for string in strings
)
print(f"There are {nice} nice strings")
@@ -103,18 +91,11 @@ def has_pairs(s: str) -> bool:
def has_letter_between(s: str) -> bool:
_my_str = zip(s, s[1:], s[2:])
for triple in _my_str:
if triple[0] == triple[-1]:
return True
return False
return any(a == c for a, _, c in zip(s, s[1:], s[2:]))
def part_2() -> None:
nice = 0
for string in strings:
if has_pairs(string) and has_letter_between(string):
nice += 1
nice = sum(has_pairs(string) and has_letter_between(string) for string in strings)
print(f"There are {nice} nicer strings")