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