Pyupgrade to Python 3.9 (#4718)

* Pyupgrade to Python 3.9

* updating DIRECTORY.md

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Christian Clauss
2021-09-07 13:37:03 +02:00
committed by GitHub
parent 5d5831bdd0
commit cecf43d648
142 changed files with 523 additions and 530 deletions

View File

@ -26,7 +26,7 @@ def solution(n: int = 1000) -> int:
0
"""
return sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0])
return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0)
if __name__ == "__main__":

View File

@ -25,7 +25,7 @@ def solution(n: int = 1000) -> int:
83700
"""
return sum([i for i in range(n) if i % 3 == 0 or i % 5 == 0])
return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0)
if __name__ == "__main__":

View File

@ -33,7 +33,7 @@ def solution(n: int = 100) -> int:
1582700
"""
sum_of_squares = sum([i * i for i in range(1, n + 1)])
sum_of_squares = sum(i * i for i in range(1, n + 1))
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
return square_of_sum - sum_of_squares

View File

@ -70,10 +70,7 @@ def solution(n: str = N) -> int:
"""
return max(
[
reduce(lambda x, y: int(x) * int(y), n[i : i + 13])
for i in range(len(n) - 12)
]
reduce(lambda x, y: int(x) * int(y), n[i : i + 13]) for i in range(len(n) - 12)
)

View File

@ -29,7 +29,7 @@ def triangle_number_generator():
def count_divisors(n):
return sum([2 for i in range(1, int(n ** 0.5) + 1) if n % i == 0 and i * i != n])
return sum(2 for i in range(1, int(n ** 0.5) + 1) if n % i == 0 and i * i != n)
def solution():

View File

@ -18,7 +18,7 @@ def solution():
"""
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
with open(file_path) as file_hand:
return str(sum([int(line) for line in file_hand]))[:10]
return str(sum(int(line) for line in file_hand))[:10]
if __name__ == "__main__":

View File

@ -25,10 +25,10 @@ that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
"""
from typing import List
from __future__ import annotations
def collatz_sequence(n: int) -> List[int]:
def collatz_sequence(n: int) -> list[int]:
"""Returns the Collatz sequence for n."""
sequence = [n]
while n != 1:
@ -54,7 +54,7 @@ def solution(n: int = 1000000) -> int:
13255
"""
result = max([(len(collatz_sequence(i)), i) for i in range(1, n)])
result = max((len(collatz_sequence(i)), i) for i in range(1, n))
return result[1]

View File

@ -28,7 +28,7 @@ def solution(num: int = 100) -> int:
>>> solution(1)
1
"""
return sum([int(x) for x in str(factorial(num))])
return sum(int(x) for x in str(factorial(num)))
if __name__ == "__main__":

View File

@ -41,11 +41,9 @@ def solution(n: int = 10000) -> int:
0
"""
total = sum(
[
i
for i in range(1, n)
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
]
i
for i in range(1, n)
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
)
return total

View File

@ -14,8 +14,9 @@ and denominator.
If the product of these four fractions is given in its lowest common
terms, find the value of the denominator.
"""
from __future__ import annotations
from fractions import Fraction
from typing import List
def is_digit_cancelling(num: int, den: int) -> bool:
@ -26,7 +27,7 @@ def is_digit_cancelling(num: int, den: int) -> bool:
return False
def fraction_list(digit_len: int) -> List[str]:
def fraction_list(digit_len: int) -> list[str]:
"""
>>> fraction_list(2)
['16/64', '19/95', '26/65', '49/98']

View File

@ -14,11 +14,10 @@ base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
"""
from typing import Union
from __future__ import annotations
def is_palindrome(n: Union[int, str]) -> bool:
def is_palindrome(n: int | str) -> bool:
"""
Return true if the input n is a palindrome.
Otherwise return false. n can be an integer or a string.

View File

@ -37,8 +37,7 @@ a has 3 digits, etc...
=> 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a
= 1002003 * a
"""
from typing import Union
from __future__ import annotations
def is_9_pandigital(n: int) -> bool:
@ -55,7 +54,7 @@ def is_9_pandigital(n: int) -> bool:
return len(s) == 9 and set(s) == set("123456789")
def solution() -> Union[int, None]:
def solution() -> int | None:
"""
Return the largest 1 to 9 pandigital 9-digital number that can be formed as the
concatenated product of an integer with (1,2,...,n) where n > 1.

View File

@ -132,7 +132,7 @@ def solution():
for seq in passed:
answer.add("".join([str(i) for i in seq]))
return max([int(x) for x in answer])
return max(int(x) for x in answer)
if __name__ == "__main__":

View File

@ -15,10 +15,10 @@ contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most
consecutive primes?
"""
from typing import List
from __future__ import annotations
def prime_sieve(limit: int) -> List[int]:
def prime_sieve(limit: int) -> list[int]:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a number 'limit'

View File

@ -15,12 +15,12 @@ with this property.
Find the smallest prime which, by replacing part of the number (not necessarily
adjacent digits) with the same digit, is part of an eight prime value family.
"""
from __future__ import annotations
from collections import Counter
from typing import List
def prime_sieve(n: int) -> List[int]:
def prime_sieve(n: int) -> list[int]:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a certain number
@ -52,7 +52,7 @@ def prime_sieve(n: int) -> List[int]:
return primes
def digit_replacements(number: int) -> List[List[int]]:
def digit_replacements(number: int) -> list[list[int]]:
"""
Returns all the possible families of digit replacements in a number which
contains at least one repeating digit

View File

@ -135,7 +135,7 @@ class PokerHand:
"""Returns the self hand"""
return self._hand
def compare_with(self, other: "PokerHand") -> str:
def compare_with(self, other: PokerHand) -> str:
"""
Determines the outcome of comparing self hand with other hand.
Returns the output as 'Win', 'Loss', 'Tie' according to the rules of
@ -220,7 +220,7 @@ class PokerHand:
else:
return name + f", {high}"
def _compare_cards(self, other: "PokerHand") -> str:
def _compare_cards(self, other: PokerHand) -> str:
# Enumerate gives us the index as well as the element of a list
for index, card_value in enumerate(self._card_values):
if card_value != other._card_values[index]:

View File

@ -30,11 +30,9 @@ def solution(a: int = 100, b: int = 100) -> int:
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
# BASE raised to the POWER
return max(
[
sum([int(x) for x in str(base ** power)])
for base in range(a)
for power in range(b)
]
sum(int(x) for x in str(base ** power))
for base in range(a)
for power in range(b)
)

View File

@ -25,23 +25,22 @@ file containing the encrypted ASCII codes, and the knowledge that the plain text
must contain common English words, decrypt the message and find the sum of the ASCII
values in the original text.
"""
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
from typing import List, Optional, Set, Tuple
VALID_CHARS: str = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
LOWERCASE_INTS: List[int] = [ord(letter) for letter in string.ascii_lowercase]
VALID_INTS: Set[int] = {ord(char) for char in VALID_CHARS}
LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase]
VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS}
COMMON_WORDS: List[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def try_key(ciphertext: List[int], key: Tuple[int, ...]) -> Optional[str]:
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None:
"""
Given an encrypted message and a possible 3-character key, decrypt the message.
If the decrypted message contains a invalid character, i.e. not an ASCII letter,
@ -66,7 +65,7 @@ def try_key(ciphertext: List[int], key: Tuple[int, ...]) -> Optional[str]:
return decoded
def filter_valid_chars(ciphertext: List[int]) -> List[str]:
def filter_valid_chars(ciphertext: list[int]) -> list[str]:
"""
Given an encrypted message, test all 3-character strings to try and find the
key. Return a list of the possible decrypted messages.
@ -77,7 +76,7 @@ def filter_valid_chars(ciphertext: List[int]) -> List[str]:
>>> text in filter_valid_chars(encoded)
True
"""
possibles: List[str] = []
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
if encoded is not None:
@ -85,7 +84,7 @@ def filter_valid_chars(ciphertext: List[int]) -> List[str]:
return possibles
def filter_common_word(possibles: List[str], common_word: str) -> List[str]:
def filter_common_word(possibles: list[str], common_word: str) -> list[str]:
"""
Given a list of possible decoded messages, narrow down the possibilities
for checking for the presence of a specified common word. Only decoded messages
@ -106,8 +105,8 @@ def solution(filename: str = "p059_cipher.txt") -> int:
>>> solution("test_cipher.txt")
3000
"""
ciphertext: List[int]
possibles: List[str]
ciphertext: list[int]
possibles: list[str]
common_word: str
decoded_text: str
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
@ -121,7 +120,7 @@ def solution(filename: str = "p059_cipher.txt") -> int:
break
decoded_text = possibles[0]
return sum([ord(char) for char in decoded_text])
return sum(ord(char) for char in decoded_text)
if __name__ == "__main__":

View File

@ -28,10 +28,10 @@ References:
Finding totients
https://en.wikipedia.org/wiki/Euler's_totient_function#Euler's_product_formula
"""
from typing import List
from __future__ import annotations
def get_totients(max_one: int) -> List[int]:
def get_totients(max_one: int) -> list[int]:
"""
Calculates a list of totients from 0 to max_one exclusive, using the
definition of Euler's product formula.

View File

@ -66,7 +66,7 @@ def sum_digit_factorials(n: int) -> int:
"""
if n in CACHE_SUM_DIGIT_FACTORIALS:
return CACHE_SUM_DIGIT_FACTORIALS[n]
ret = sum([DIGIT_FACTORIALS[let] for let in str(n)])
ret = sum(DIGIT_FACTORIALS[let] for let in str(n))
CACHE_SUM_DIGIT_FACTORIALS[n] = ret
return ret

View File

@ -12,10 +12,10 @@ It is possible to write ten as the sum of primes in exactly five different ways:
What is the first value which can be written as the sum of primes in over
five thousand different ways?
"""
from __future__ import annotations
from functools import lru_cache
from math import ceil
from typing import Optional, Set
NUM_PRIMES = 100
@ -30,7 +30,7 @@ for prime in range(3, ceil(NUM_PRIMES ** 0.5), 2):
@lru_cache(maxsize=100)
def partition(number_to_partition: int) -> Set[int]:
def partition(number_to_partition: int) -> set[int]:
"""
Return a set of integers corresponding to unique prime partitions of n.
The unique prime partitions can be represented as unique prime decompositions,
@ -47,7 +47,7 @@ def partition(number_to_partition: int) -> Set[int]:
elif number_to_partition == 0:
return {1}
ret: Set[int] = set()
ret: set[int] = set()
prime: int
sub: int
@ -60,7 +60,7 @@ def partition(number_to_partition: int) -> Set[int]:
return ret
def solution(number_unique_partitions: int = 5000) -> Optional[int]:
def solution(number_unique_partitions: int = 5000) -> int | None:
"""
Return the smallest integer that can be written as the sum of primes in over
m unique ways.

View File

@ -27,7 +27,7 @@ def solution() -> int:
if len(str(sqrt_number)) > 1:
answer += int(str(sqrt_number)[0])
sqrt_number = str(sqrt_number)[2:101]
answer += sum([int(x) for x in sqrt_number])
answer += sum(int(x) for x in sqrt_number)
return answer

View File

@ -22,7 +22,7 @@ def solution(filename: str = "matrix.txt") -> int:
>>> solution()
427337
"""
with open(os.path.join(os.path.dirname(__file__), filename), "r") as in_file:
with open(os.path.join(os.path.dirname(__file__), filename)) as in_file:
data = in_file.read()
grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()]

View File

@ -44,10 +44,9 @@ Solution:
Reference: https://en.wikipedia.org/wiki/Triangular_number
https://en.wikipedia.org/wiki/Quadratic_formula
"""
from __future__ import annotations
from math import ceil, floor, sqrt
from typing import List
def solution(target: int = 2000000) -> int:
@ -61,7 +60,7 @@ def solution(target: int = 2000000) -> int:
>>> solution(2000000000)
86595
"""
triangle_numbers: List[int] = [0]
triangle_numbers: list[int] = [0]
idx: int
for idx in range(1, ceil(sqrt(target * 2) * 1.1)):

View File

@ -125,7 +125,7 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
savings = 0
file1 = open(os.path.dirname(__file__) + roman_numerals_filename, "r")
file1 = open(os.path.dirname(__file__) + roman_numerals_filename)
lines = file1.readlines()
for line in lines:
original = line.strip()

View File

@ -41,11 +41,11 @@ Consider the following tenth degree polynomial generating function:
Find the sum of FITs for the BOPs.
"""
from __future__ import annotations
from typing import Callable, Union
from typing import Callable, List, Union
Matrix = List[List[Union[float, int]]]
Matrix = list[list[Union[float, int]]]
def solve(matrix: Matrix, vector: Matrix) -> Matrix:
@ -78,9 +78,9 @@ def solve(matrix: Matrix, vector: Matrix) -> Matrix:
col = 0
while row < size and col < size:
# pivoting
pivot_row = max(
[(abs(augmented[row2][col]), row2) for row2 in range(col, size)]
)[1]
pivot_row = max((abs(augmented[row2][col]), row2) for row2 in range(col, size))[
1
]
if augmented[pivot_row][col] == 0:
col += 1
continue
@ -109,7 +109,7 @@ def solve(matrix: Matrix, vector: Matrix) -> Matrix:
]
def interpolate(y_list: List[int]) -> Callable[[int], int]:
def interpolate(y_list: list[int]) -> Callable[[int], int]:
"""
Given a list of data points (1,y0),(2,y1), ..., return a function that
interpolates the data points. We find the coefficients of the interpolating
@ -195,9 +195,9 @@ def solution(func: Callable[[int], int] = question_function, order: int = 10) ->
>>> solution(lambda n: n ** 3, 3)
74
"""
data_points: List[int] = [func(x_val) for x_val in range(1, order + 1)]
data_points: list[int] = [func(x_val) for x_val in range(1, order + 1)]
polynomials: List[Callable[[int], int]] = [
polynomials: list[Callable[[int], int]] = [
interpolate(data_points[:max_coeff]) for max_coeff in range(1, order + 1)
]

View File

@ -18,12 +18,12 @@ the number of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the
example given above.
"""
from __future__ import annotations
from pathlib import Path
from typing import List, Tuple
def vector_product(point1: Tuple[int, int], point2: Tuple[int, int]) -> int:
def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int:
"""
Return the 2-d vector product of two vectors.
>>> vector_product((1, 2), (-5, 0))
@ -43,9 +43,9 @@ def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> boo
>>> contains_origin(-175, 41, -421, -714, 574, -645)
False
"""
point_a: Tuple[int, int] = (x1, y1)
point_a_to_b: Tuple[int, int] = (x2 - x1, y2 - y1)
point_a_to_c: Tuple[int, int] = (x3 - x1, y3 - y1)
point_a: tuple[int, int] = (x1, y1)
point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1)
point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1)
a: float = -vector_product(point_a, point_a_to_b) / vector_product(
point_a_to_c, point_a_to_b
)
@ -64,12 +64,12 @@ def solution(filename: str = "p102_triangles.txt") -> int:
"""
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
triangles: List[List[int]] = []
triangles: list[list[int]] = []
for line in data.strip().split("\n"):
triangles.append([int(number) for number in line.split(",")])
ret: int = 0
triangle: List[int]
triangle: list[int]
for triangle in triangles:
ret += contains_origin(*triangle)

View File

@ -27,11 +27,12 @@ Solution:
We use Prim's algorithm to find a Minimum Spanning Tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
"""
from __future__ import annotations
import os
from typing import Dict, List, Mapping, Set, Tuple
from typing import Mapping
EdgeT = Tuple[int, int]
EdgeT = tuple[int, int]
class Graph:
@ -39,9 +40,9 @@ class Graph:
A class representing an undirected weighted graph.
"""
def __init__(self, vertices: Set[int], edges: Mapping[EdgeT, int]) -> None:
self.vertices: Set[int] = vertices
self.edges: Dict[EdgeT, int] = {
def __init__(self, vertices: set[int], edges: Mapping[EdgeT, int]) -> None:
self.vertices: set[int] = vertices
self.edges: dict[EdgeT, int] = {
(min(edge), max(edge)): weight for edge, weight in edges.items()
}
@ -59,7 +60,7 @@ class Graph:
self.vertices.add(edge[1])
self.edges[(min(edge), max(edge))] = weight
def prims_algorithm(self) -> "Graph":
def prims_algorithm(self) -> Graph:
"""
Run Prim's algorithm to find the minimum spanning tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
@ -98,13 +99,13 @@ def solution(filename: str = "p107_network.txt") -> int:
"""
script_dir: str = os.path.abspath(os.path.dirname(__file__))
network_file: str = os.path.join(script_dir, filename)
adjacency_matrix: List[List[str]]
edges: Dict[EdgeT, int] = dict()
data: List[str]
adjacency_matrix: list[list[str]]
edges: dict[EdgeT, int] = dict()
data: list[str]
edge1: int
edge2: int
with open(network_file, "r") as f:
with open(network_file) as f:
data = f.read().strip().split("\n")
adjaceny_matrix = [line.split(",") for line in data]

View File

@ -23,7 +23,7 @@ def digit_sum(n: int) -> int:
>>> digit_sum(78910)
25
"""
return sum([int(digit) for digit in str(n)])
return sum(int(digit) for digit in str(n))
def solution(n: int = 30) -> int:

View File

@ -37,8 +37,9 @@ So it could be simplified as,
r = 2pn when n is odd
r = 2 when n is even.
"""
from __future__ import annotations
from typing import Dict, Generator
from typing import Generator
def sieve() -> Generator[int, None, None]:
@ -60,7 +61,7 @@ def sieve() -> Generator[int, None, None]:
>>> next(primes)
13
"""
factor_map: Dict[int, int] = {}
factor_map: dict[int, int] = {}
prime = 2
while True:
factor = factor_map.pop(prime, None)

View File

@ -44,11 +44,10 @@ we get the right numerator and denominator.
Reference:
https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem
"""
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
from typing import Tuple
def is_sq(number: int) -> bool:
@ -68,7 +67,7 @@ def is_sq(number: int) -> bool:
def add_three(
x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int
) -> Tuple[int, int]:
) -> tuple[int, int]:
"""
Given the numerators and denominators of three fractions, return the
numerator and denominator of their sum in lowest form.
@ -100,7 +99,7 @@ def solution(order: int = 35) -> int:
unique_s: set = set()
hcf: int
total: Fraction = Fraction(0)
fraction_sum: Tuple[int, int]
fraction_sum: tuple[int, int]
for x_num in range(1, order + 1):
for x_den in range(x_num + 1, order + 1):

View File

@ -27,12 +27,12 @@ Pascal's triangle.
References:
- https://en.wikipedia.org/wiki/Pascal%27s_triangle
"""
from __future__ import annotations
import math
from typing import List, Set
def get_pascal_triangle_unique_coefficients(depth: int) -> Set[int]:
def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]:
"""
Returns the unique coefficients of a Pascal's triangle of depth "depth".
@ -61,7 +61,7 @@ def get_pascal_triangle_unique_coefficients(depth: int) -> Set[int]:
return coefficients
def get_primes_squared(max_number: int) -> List[int]:
def get_primes_squared(max_number: int) -> list[int]:
"""
Calculates all primes between 2 and round(sqrt(max_number)) and returns
them squared up.
@ -92,7 +92,7 @@ def get_primes_squared(max_number: int) -> List[int]:
def get_squared_primes_to_use(
num_to_look: int, squared_primes: List[int], previous_index: int
num_to_look: int, squared_primes: list[int], previous_index: int
) -> int:
"""
Returns an int indicating the last index on which squares of primes
@ -128,8 +128,8 @@ def get_squared_primes_to_use(
def get_squarefree(
unique_coefficients: Set[int], squared_primes: List[int]
) -> Set[int]:
unique_coefficients: set[int], squared_primes: list[int]
) -> set[int]:
"""
Calculates the squarefree numbers inside unique_coefficients given a
list of square of primes.