instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Create Google-style docstrings for my code |
def solution(n: int = 1000) -> int:
total = 0
num = 0
while 1:
num += 3
if num >= n:
break
total += num
num += 2
if num >= n:
break
total += num
num += 1
if num >= n:
break
total += num
num += 3
if num >= n:
break
total += num
num += 1
if num >= n:
break
total += num
num += 2
if num >= n:
break
total += num
num += 3
if num >= n:
break
total += num
return total
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,30 @@+"""
+Project Euler Problem 1: https://projecteuler.net/problem=1
+
+Multiples of 3 and 5
+
+If we list all the natural numbers below 10 that are multiples of 3 or 5,
+we get 3, 5, 6 and 9. The sum of these multiples is 23.
+
+Find the sum of all the multiples of 3 or 5 below 1000.
+"""
def solution(n: int = 1000) -> int:
+ """
+ This solution is based on the pattern that the successive numbers in the
+ series follow: 0+3,+2,+1,+3,+1,+2,+3.
+ Returns the sum of all the multiples of 3 or 5 below n.
+
+ >>> solution(3)
+ 0
+ >>> solution(4)
+ 3
+ >>> solution(10)
+ 23
+ >>> solution(600)
+ 83700
+ """
total = 0
num = 0
@@ -37,4 +61,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol3.py |
Write documentation strings for class attributes |
def solution(n: int = 4000000) -> int:
i = 1
j = 2
total = 0
while j <= n:
if j % 2 == 0:
total += j
i, j = j, i + j
return total
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,37 @@+"""
+Project Euler Problem 2: https://projecteuler.net/problem=2
+
+Even Fibonacci Numbers
+
+Each new term in the Fibonacci sequence is generated by adding the previous
+two terms. By starting with 1 and 2, the first 10 terms will be:
+
+1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+By considering the terms in the Fibonacci sequence whose values do not exceed
+four million, find the sum of the even-valued terms.
+
+References:
+ - https://en.wikipedia.org/wiki/Fibonacci_number
+"""
def solution(n: int = 4000000) -> int:
+ """
+ Returns the sum of all even fibonacci sequence elements that are lower
+ or equal to n.
+
+ >>> solution(10)
+ 10
+ >>> solution(15)
+ 10
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 0
+ >>> solution(34)
+ 44
+ """
i = 1
j = 2
@@ -14,4 +45,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_002/sol1.py |
Generate docstrings for exported functions |
def solution(n: int = 4000000) -> int:
fib = [0, 1]
i = 0
while fib[i] <= n:
fib.append(fib[i] + fib[i + 1])
if fib[i + 2] > n:
break
i += 1
total = 0
for j in range(len(fib) - 1):
if fib[j] % 2 == 0:
total += fib[j]
return total
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,37 @@+"""
+Project Euler Problem 2: https://projecteuler.net/problem=2
+
+Even Fibonacci Numbers
+
+Each new term in the Fibonacci sequence is generated by adding the previous
+two terms. By starting with 1 and 2, the first 10 terms will be:
+
+1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+By considering the terms in the Fibonacci sequence whose values do not exceed
+four million, find the sum of the even-valued terms.
+
+References:
+ - https://en.wikipedia.org/wiki/Fibonacci_number
+"""
def solution(n: int = 4000000) -> int:
+ """
+ Returns the sum of all even fibonacci sequence elements that are lower
+ or equal to n.
+
+ >>> solution(10)
+ 10
+ >>> solution(15)
+ 10
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 0
+ >>> solution(34)
+ 44
+ """
fib = [0, 1]
i = 0
@@ -18,4 +49,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_002/sol5.py |
Add docstrings to clarify complex logic |
def solution(n: int = 600851475143) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 2
ans = 0
if n == 2:
return 2
while n > 2:
while n % i != 0:
i += 1
ans = i
while n % i == 0:
n = n // i
i += 1
return int(ans)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,46 @@+"""
+Project Euler Problem 3: https://projecteuler.net/problem=3
+
+Largest prime factor
+
+The prime factors of 13195 are 5, 7, 13 and 29.
+
+What is the largest prime factor of the number 600851475143?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
+"""
def solution(n: int = 600851475143) -> int:
+ """
+ Returns the largest prime factor of a given number n.
+
+ >>> solution(13195)
+ 29
+ >>> solution(10)
+ 5
+ >>> solution(17)
+ 17
+ >>> solution(3.4)
+ 3
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ """
try:
n = int(n)
@@ -23,4 +63,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_003/sol3.py |
Turn comments into proper docstrings |
def solution(n: int = 998001) -> int:
# fetches the next number
for number in range(n - 1, 9999, -1):
str_number = str(number)
# checks whether 'str_number' is a palindrome.
if str_number == str_number[::-1]:
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while divisor != 99:
if (number % divisor == 0) and (len(str(number // divisor)) == 3.0):
return number
divisor -= 1
raise ValueError("That number is larger than our acceptable range.")
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,34 @@+"""
+Project Euler Problem 4: https://projecteuler.net/problem=4
+
+Largest palindrome product
+
+A palindromic number reads the same both ways. The largest palindrome made
+from the product of two 2-digit numbers is 9009 = 91 x 99.
+
+Find the largest palindrome made from the product of two 3-digit numbers.
+
+References:
+ - https://en.wikipedia.org/wiki/Palindromic_number
+"""
def solution(n: int = 998001) -> int:
+ """
+ Returns the largest palindrome made from the product of two 3-digit
+ numbers which is less than n.
+
+ >>> solution(20000)
+ 19591
+ >>> solution(30000)
+ 29992
+ >>> solution(40000)
+ 39893
+ >>> solution(10000)
+ Traceback (most recent call last):
+ ...
+ ValueError: That number is larger than our acceptable range.
+ """
# fetches the next number
for number in range(n - 1, 9999, -1):
@@ -20,4 +48,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_004/sol1.py |
Generate consistent docstrings |
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(n: int = 600851475143) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
max_number = 0
if is_prime(n):
return n
while n % 2 == 0:
n //= 2
if is_prime(n):
return n
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
if is_prime(n // i):
max_number = n // i
break
elif is_prime(i):
max_number = i
return max_number
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,38 @@+"""
+Project Euler Problem 3: https://projecteuler.net/problem=3
+
+Largest prime factor
+
+The prime factors of 13195 are 5, 7, 13 and 29.
+
+What is the largest prime factor of the number 600851475143?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,6 +49,34 @@
def solution(n: int = 600851475143) -> int:
+ """
+ Returns the largest prime factor of a given number n.
+
+ >>> solution(13195)
+ 29
+ >>> solution(10)
+ 5
+ >>> solution(17)
+ 17
+ >>> solution(3.4)
+ 3
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ """
try:
n = int(n)
@@ -44,4 +102,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_003/sol1.py |
Document this code for team use |
def solution(n: int = 600851475143) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
prime = 1
i = 2
while i * i <= n:
while n % i == 0:
prime = i
n //= i
i += 1
if n > 1:
prime = n
return int(prime)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,46 @@+"""
+Project Euler Problem 3: https://projecteuler.net/problem=3
+
+Largest prime factor
+
+The prime factors of 13195 are 5, 7, 13 and 29.
+
+What is the largest prime factor of the number 600851475143?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
+"""
def solution(n: int = 600851475143) -> int:
+ """
+ Returns the largest prime factor of a given number n.
+
+ >>> solution(13195)
+ 29
+ >>> solution(10)
+ 5
+ >>> solution(17)
+ 17
+ >>> solution(3.4)
+ 3
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ """
try:
n = int(n)
@@ -21,4 +61,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_003/sol2.py |
Add docstrings for internal functions | from maths.greatest_common_divisor import greatest_common_divisor
"""
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
- https://en.wikipedia.org/wiki/Euclidean_algorithm
- https://en.wikipedia.org/wiki/Least_common_multiple
"""
def lcm(x: int, y: int) -> int:
return (x * y) // greatest_common_divisor(x, y)
def solution(n: int = 20) -> int:
g = 1
for i in range(1, n + 1):
g = lcm(g, i)
return g
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -19,11 +19,36 @@
def lcm(x: int, y: int) -> int:
+ """
+ Least Common Multiple.
+
+ Using the property that lcm(a, b) * greatest_common_divisor(a, b) = a*b
+
+ >>> lcm(3, 15)
+ 15
+ >>> lcm(1, 27)
+ 27
+ >>> lcm(13, 27)
+ 351
+ >>> lcm(64, 48)
+ 192
+ """
return (x * y) // greatest_common_divisor(x, y)
def solution(n: int = 20) -> int:
+ """
+ Returns the smallest positive number that is evenly divisible (divisible
+ with no remainder) by all of the numbers from 1 to n.
+
+ >>> solution(10)
+ 2520
+ >>> solution(15)
+ 360360
+ >>> solution(22)
+ 232792560
+ """
g = 1
for i in range(1, n + 1):
@@ -32,4 +57,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_005/sol2.py |
Write reusable docstrings |
import math
from decimal import Decimal, getcontext
def solution(n: int = 4000000) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
getcontext().prec = 100
phi = (Decimal(5) ** Decimal("0.5") + 1) / Decimal(2)
index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2
num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2)
total = num // 2
return int(total)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,9 +1,58 @@+"""
+Project Euler Problem 2: https://projecteuler.net/problem=2
+
+Even Fibonacci Numbers
+
+Each new term in the Fibonacci sequence is generated by adding the previous
+two terms. By starting with 1 and 2, the first 10 terms will be:
+
+1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+By considering the terms in the Fibonacci sequence whose values do not exceed
+four million, find the sum of the even-valued terms.
+
+References:
+ - https://en.wikipedia.org/wiki/Fibonacci_number
+"""
import math
from decimal import Decimal, getcontext
def solution(n: int = 4000000) -> int:
+ """
+ Returns the sum of all even fibonacci sequence elements that are lower
+ or equal to n.
+
+ >>> solution(10)
+ 10
+ >>> solution(15)
+ 10
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 0
+ >>> solution(34)
+ 44
+ >>> solution(3.4)
+ 2
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ """
try:
n = int(n)
@@ -21,4 +70,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_002/sol4.py |
Add docstrings to clarify complex logic |
def solution(n: int = 20) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
return None
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,49 @@+"""
+Project Euler Problem 5: https://projecteuler.net/problem=5
+
+Smallest multiple
+
+2520 is the smallest number that can be divided by each of the numbers
+from 1 to 10 without any remainder.
+
+What is the smallest positive number that is _evenly divisible_ by all
+of the numbers from 1 to 20?
+
+References:
+ - https://en.wiktionary.org/wiki/evenly_divisible
+"""
def solution(n: int = 20) -> int:
+ """
+ Returns the smallest positive number that is evenly divisible (divisible
+ with no remainder) by all of the numbers from 1 to n.
+
+ >>> solution(10)
+ 2520
+ >>> solution(15)
+ 360360
+ >>> solution(22)
+ 232792560
+ >>> solution(3.4)
+ 6
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter n must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter n must be int or castable to int.
+ """
try:
n = int(n)
@@ -24,4 +67,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_005/sol1.py |
Document classes and their methods |
def solution(n: int = 4000000) -> int:
even_fibs = []
a, b = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(b)
a, b = b, a + b
return sum(even_fibs)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,37 @@+"""
+Project Euler Problem 2: https://projecteuler.net/problem=2
+
+Even Fibonacci Numbers
+
+Each new term in the Fibonacci sequence is generated by adding the previous
+two terms. By starting with 1 and 2, the first 10 terms will be:
+
+1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+By considering the terms in the Fibonacci sequence whose values do not exceed
+four million, find the sum of the even-valued terms.
+
+References:
+ - https://en.wikipedia.org/wiki/Fibonacci_number
+"""
def solution(n: int = 4000000) -> int:
+ """
+ Returns the sum of all even fibonacci sequence elements that are lower
+ or equal to n.
+
+ >>> solution(10)
+ 10
+ >>> solution(15)
+ 10
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 0
+ >>> solution(34)
+ 44
+ """
even_fibs = []
a, b = 0, 1
@@ -12,4 +43,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_002/sol2.py |
Add well-formatted docstrings |
def solution(n: int = 100) -> int:
sum_of_squares = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,36 @@+"""
+Project Euler Problem 6: https://projecteuler.net/problem=6
+
+Sum square difference
+
+The sum of the squares of the first ten natural numbers is,
+ 1^2 + 2^2 + ... + 10^2 = 385
+
+The square of the sum of the first ten natural numbers is,
+ (1 + 2 + ... + 10)^2 = 55^2 = 3025
+
+Hence the difference between the sum of the squares of the first ten
+natural numbers and the square of the sum is 3025 - 385 = 2640.
+
+Find the difference between the sum of the squares of the first one
+hundred natural numbers and the square of the sum.
+"""
def solution(n: int = 100) -> int:
+ """
+ Returns the difference between the sum of the squares of the first n
+ natural numbers and the square of the sum.
+
+ >>> solution(10)
+ 2640
+ >>> solution(15)
+ 13160
+ >>> solution(20)
+ 41230
+ >>> solution(50)
+ 1582700
+ """
sum_of_squares = 0
sum_of_ints = 0
@@ -11,4 +41,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_006/sol1.py |
Create docstrings for each class method |
from math import exp
def f(x: float) -> float:
return 8 * x - 2 * exp(-x)
def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:
x0 = lower_bound
x1 = upper_bound
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1
if __name__ == "__main__":
print(f"Example: {secant_method(1, 3, 2)}") | --- +++ @@ -1,12 +1,24 @@+"""
+Implementing Secant method in Python
+Author: dimgrichr
+"""
from math import exp
def f(x: float) -> float:
+ """
+ >>> f(5)
+ 39.98652410600183
+ """
return 8 * x - 2 * exp(-x)
def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:
+ """
+ >>> secant_method(1, 3, 2)
+ 0.2139409276214589
+ """
x0 = lower_bound
x1 = upper_bound
for _ in range(repeats):
@@ -15,4 +27,4 @@
if __name__ == "__main__":
- print(f"Example: {secant_method(1, 3, 2)}")+ print(f"Example: {secant_method(1, 3, 2)}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/secant_method.py |
Create docstrings for each class method |
from math import sqrt
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(nth: int = 10001) -> int:
count = 0
number = 1
while count != nth and number < 3:
number += 1
if is_prime(number):
count += 1
while count != nth:
number += 2
if is_prime(number):
count += 1
return number
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,39 @@+"""
+Project Euler Problem 7: https://projecteuler.net/problem=7
+
+10001st prime
+
+By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
+can see that the 6th prime is 13.
+
+What is the 10001st prime number?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+"""
from math import sqrt
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,6 +50,22 @@
def solution(nth: int = 10001) -> int:
+ """
+ Returns the n-th prime number.
+
+ >>> solution(6)
+ 13
+ >>> solution(1)
+ 2
+ >>> solution(3)
+ 5
+ >>> solution(20)
+ 71
+ >>> solution(50)
+ 229
+ >>> solution(100)
+ 541
+ """
count = 0
number = 1
@@ -34,4 +81,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_007/sol1.py |
Generate docstrings for script automation |
import math
def solution(n: int = 100) -> int:
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
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,38 @@+"""
+Project Euler Problem 6: https://projecteuler.net/problem=6
+
+Sum square difference
+
+The sum of the squares of the first ten natural numbers is,
+ 1^2 + 2^2 + ... + 10^2 = 385
+
+The square of the sum of the first ten natural numbers is,
+ (1 + 2 + ... + 10)^2 = 55^2 = 3025
+
+Hence the difference between the sum of the squares of the first ten
+natural numbers and the square of the sum is 3025 - 385 = 2640.
+
+Find the difference between the sum of the squares of the first one
+hundred natural numbers and the square of the sum.
+"""
import math
def solution(n: int = 100) -> int:
+ """
+ Returns the difference between the sum of the squares of the first n
+ natural numbers and the square of the sum.
+
+ >>> solution(10)
+ 2640
+ >>> solution(15)
+ 13160
+ >>> solution(20)
+ 41230
+ >>> solution(50)
+ 1582700
+ """
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))
@@ -10,4 +40,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_006/sol3.py |
Replace inline comments with docstrings |
def solution(n: int = 100) -> int:
sum_cubes = (n * (n + 1) // 2) ** 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,36 @@+"""
+Project Euler Problem 6: https://projecteuler.net/problem=6
+
+Sum square difference
+
+The sum of the squares of the first ten natural numbers is,
+ 1^2 + 2^2 + ... + 10^2 = 385
+
+The square of the sum of the first ten natural numbers is,
+ (1 + 2 + ... + 10)^2 = 55^2 = 3025
+
+Hence the difference between the sum of the squares of the first ten
+natural numbers and the square of the sum is 3025 - 385 = 2640.
+
+Find the difference between the sum of the squares of the first one
+hundred natural numbers and the square of the sum.
+"""
def solution(n: int = 100) -> int:
+ """
+ Returns the difference between the sum of the squares of the first n
+ natural numbers and the square of the sum.
+
+ >>> solution(10)
+ 2640
+ >>> solution(15)
+ 13160
+ >>> solution(20)
+ 41230
+ >>> solution(50)
+ 1582700
+ """
sum_cubes = (n * (n + 1) // 2) ** 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
@@ -8,4 +38,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_006/sol2.py |
Write docstrings for data processing functions |
def solution(n: int = 998001) -> int:
answer = 0
for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100
for j in range(999, 99, -1):
product_string = str(i * j)
if product_string == product_string[::-1] and i * j < n:
answer = max(answer, i * j)
return answer
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,30 @@+"""
+Project Euler Problem 4: https://projecteuler.net/problem=4
+
+Largest palindrome product
+
+A palindromic number reads the same both ways. The largest palindrome made
+from the product of two 2-digit numbers is 9009 = 91 x 99.
+
+Find the largest palindrome made from the product of two 3-digit numbers.
+
+References:
+ - https://en.wikipedia.org/wiki/Palindromic_number
+"""
def solution(n: int = 998001) -> int:
+ """
+ Returns the largest palindrome made from the product of two 3-digit
+ numbers which is less than n.
+
+ >>> solution(20000)
+ 19591
+ >>> solution(30000)
+ 29992
+ >>> solution(40000)
+ 39893
+ """
answer = 0
for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100
@@ -12,4 +36,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_004/sol2.py |
Add docstrings to meet PEP guidelines |
def perfect(number: int) -> bool:
if not isinstance(number, int):
raise ValueError("number must be an integer")
if number <= 0:
return False
return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number
if __name__ == "__main__":
from doctest import testmod
testmod()
print("Program to check whether a number is a Perfect number or not...")
try:
number = int(input("Enter a positive integer: ").strip())
except ValueError:
msg = "number must be an integer"
raise ValueError(msg)
print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.") | --- +++ @@ -1,6 +1,70 @@+"""
+== Perfect Number ==
+In number theory, a perfect number is a positive integer that is equal to the sum of
+its positive divisors, excluding the number itself.
+For example: 6 ==> divisors[1, 2, 3, 6]
+ Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6
+ So, 6 is a Perfect Number
+
+Other examples of Perfect Numbers: 28, 486, ...
+
+https://en.wikipedia.org/wiki/Perfect_number
+"""
def perfect(number: int) -> bool:
+ """
+ Check if a number is a perfect number.
+
+ A perfect number is a positive integer that is equal to the sum of its proper
+ divisors (excluding itself).
+
+ Args:
+ number: The number to be checked.
+
+ Returns:
+ True if the number is a perfect number otherwise, False.
+ Start from 1 because dividing by 0 will raise ZeroDivisionError.
+ A number at most can be divisible by the half of the number except the number
+ itself. For example, 6 is at most can be divisible by 3 except by 6 itself.
+ Examples:
+ >>> perfect(27)
+ False
+ >>> perfect(28)
+ True
+ >>> perfect(29)
+ False
+ >>> perfect(6)
+ True
+ >>> perfect(12)
+ False
+ >>> perfect(496)
+ True
+ >>> perfect(8128)
+ True
+ >>> perfect(0)
+ False
+ >>> perfect(-1)
+ False
+ >>> perfect(33550336) # Large perfect number
+ True
+ >>> perfect(33550337) # Just above a large perfect number
+ False
+ >>> perfect(1) # Edge case: 1 is not a perfect number
+ False
+ >>> perfect("123") # String representation of a number
+ Traceback (most recent call last):
+ ...
+ ValueError: number must be an integer
+ >>> perfect(12.34)
+ Traceback (most recent call last):
+ ...
+ ValueError: number must be an integer
+ >>> perfect("Hello")
+ Traceback (most recent call last):
+ ...
+ ValueError: number must be an integer
+ """
if not isinstance(number, int):
raise ValueError("number must be an integer")
if number <= 0:
@@ -19,4 +83,4 @@ msg = "number must be an integer"
raise ValueError(msg)
- print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")+ print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/perfect_number.py |
Please document this code using docstrings |
import itertools
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def prime_generator():
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(nth: int = 10001) -> int:
return next(itertools.islice(prime_generator(), nth - 1, nth))
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,9 +1,40 @@+"""
+Project Euler Problem 7: https://projecteuler.net/problem=7
+
+10001st prime
+
+By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
+can see that the 6th prime is 13.
+
+What is the 10001st prime number?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+"""
import itertools
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -20,6 +51,9 @@
def prime_generator():
+ """
+ Generate a sequence of prime numbers
+ """
num = 2
while True:
@@ -29,8 +63,24 @@
def solution(nth: int = 10001) -> int:
+ """
+ Returns the n-th prime number.
+
+ >>> solution(6)
+ 13
+ >>> solution(1)
+ 2
+ >>> solution(3)
+ 5
+ >>> solution(20)
+ 71
+ >>> solution(50)
+ 229
+ >>> solution(100)
+ 541
+ """
return next(itertools.islice(prime_generator(), nth - 1, nth))
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_007/sol3.py |
Add docstrings to existing functions |
def power(base: int, exponent: int) -> float:
return base * power(base, (exponent - 1)) if exponent else 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print("Raise base to the power of exponent using recursion...")
base = int(input("Enter the base: ").strip())
exponent = int(input("Enter the exponent: ").strip())
result = power(base, abs(exponent))
if exponent < 0: # power() does not properly deal w/ negative exponents
result = 1 / result
print(f"{base} to the power of {exponent} is {result}") | --- +++ @@ -1,6 +1,52 @@+"""
+== Raise base to the power of exponent using recursion ==
+ Input -->
+ Enter the base: 3
+ Enter the exponent: 4
+ Output -->
+ 3 to the power of 4 is 81
+ Input -->
+ Enter the base: 2
+ Enter the exponent: 0
+ Output -->
+ 2 to the power of 0 is 1
+"""
def power(base: int, exponent: int) -> float:
+ """
+ Calculate the power of a base raised to an exponent.
+
+ >>> power(3, 4)
+ 81
+ >>> power(2, 0)
+ 1
+ >>> all(power(base, exponent) == pow(base, exponent)
+ ... for base in range(-10, 10) for exponent in range(10))
+ True
+ >>> power('a', 1)
+ 'a'
+ >>> power('a', 2)
+ Traceback (most recent call last):
+ ...
+ TypeError: can't multiply sequence by non-int of type 'str'
+ >>> power('a', 'b')
+ Traceback (most recent call last):
+ ...
+ TypeError: unsupported operand type(s) for -: 'str' and 'int'
+ >>> power(2, -1)
+ Traceback (most recent call last):
+ ...
+ RecursionError: maximum recursion depth exceeded
+ >>> power(0, 0)
+ 1
+ >>> power(0, 1)
+ 0
+ >>> power(5,6)
+ 15625
+ >>> power(23, 12)
+ 21914624432020321
+ """
return base * power(base, (exponent - 1)) if exponent else 1
@@ -14,4 +60,4 @@ result = power(base, abs(exponent))
if exponent < 0: # power() does not properly deal w/ negative exponents
result = 1 / result
- print(f"{base} to the power of {exponent} is {result}")+ print(f"{base} to the power of {exponent} is {result}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/power_using_recursion.py |
Add docstrings following best practices |
import sys
N = (
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450"
)
def str_eval(s: str) -> int:
product = 1
for digit in s:
product *= int(digit)
return product
def solution(n: str = N) -> int:
largest_product = -sys.maxsize - 1
substr = n[:13]
cur_index = 13
while cur_index < len(n) - 13:
if int(n[cur_index]) >= int(substr[0]):
substr = substr[1:] + n[cur_index]
cur_index += 1
else:
largest_product = max(largest_product, str_eval(substr))
substr = n[cur_index : cur_index + 13]
cur_index += 13
return largest_product
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,3 +1,35 @@+"""
+Project Euler Problem 8: https://projecteuler.net/problem=8
+
+Largest product in a series
+
+The four adjacent digits in the 1000-digit number that have the greatest
+product are 9 x 9 x 8 x 9 = 5832.
+
+ 73167176531330624919225119674426574742355349194934
+ 96983520312774506326239578318016984801869478851843
+ 85861560789112949495459501737958331952853208805511
+ 12540698747158523863050715693290963295227443043557
+ 66896648950445244523161731856403098711121722383113
+ 62229893423380308135336276614282806444486645238749
+ 30358907296290491560440772390713810515859307960866
+ 70172427121883998797908792274921901699720888093776
+ 65727333001053367881220235421809751254540594752243
+ 52584907711670556013604839586446706324415722155397
+ 53697817977846174064955149290862569321978468622482
+ 83972241375657056057490261407972968652414535100474
+ 82166370484403199890008895243450658541227588666881
+ 16427171479924442928230863465674813919123162824586
+ 17866458359124566529476545682848912883142607690042
+ 24219022671055626321111109370544217506941658960408
+ 07198403850962455444362981230987879927244284909188
+ 84580156166097919133875499200524063689912560717606
+ 05886116467109405077541002256983155200055935729725
+ 71636269561882670428252483600823257530420752963450
+
+Find the thirteen adjacent digits in the 1000-digit number that have the
+greatest product. What is the value of this product?
+"""
import sys
@@ -26,6 +58,14 @@
def str_eval(s: str) -> int:
+ """
+ Returns product of digits in given string n
+
+ >>> str_eval("987654321")
+ 362880
+ >>> str_eval("22222222")
+ 256
+ """
product = 1
for digit in s:
@@ -34,6 +74,10 @@
def solution(n: str = N) -> int:
+ """
+ Find the thirteen adjacent digits in the 1000-digit number n that have
+ the greatest product and returns it.
+ """
largest_product = -sys.maxsize - 1
substr = n[:13]
@@ -50,4 +94,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_008/sol3.py |
Create docstrings for each class method |
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(nth: int = 10001) -> int:
try:
nth = int(nth)
except (TypeError, ValueError):
raise TypeError("Parameter nth must be int or castable to int.") from None
if nth <= 0:
raise ValueError("Parameter nth must be greater than or equal to one.")
primes: list[int] = []
num = 2
while len(primes) < nth:
if is_prime(num):
primes.append(num)
num += 1
else:
num += 1
return primes[len(primes) - 1]
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,39 @@+"""
+Project Euler Problem 7: https://projecteuler.net/problem=7
+
+10001st prime
+
+By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
+can see that the 6th prime is 13.
+
+What is the 10001st prime number?
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,6 +50,40 @@
def solution(nth: int = 10001) -> int:
+ """
+ Returns the n-th prime number.
+
+ >>> solution(6)
+ 13
+ >>> solution(1)
+ 2
+ >>> solution(3)
+ 5
+ >>> solution(20)
+ 71
+ >>> solution(50)
+ 229
+ >>> solution(100)
+ 541
+ >>> solution(3.4)
+ 5
+ >>> solution(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter nth must be greater than or equal to one.
+ >>> solution(-17)
+ Traceback (most recent call last):
+ ...
+ ValueError: Parameter nth must be greater than or equal to one.
+ >>> solution([])
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter nth must be int or castable to int.
+ >>> solution("asd")
+ Traceback (most recent call last):
+ ...
+ TypeError: Parameter nth must be int or castable to int.
+ """
try:
nth = int(nth)
@@ -38,4 +103,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_007/sol2.py |
Write Python docstrings for this snippet | def multiplicative_persistence(num: int) -> int:
if not isinstance(num, int):
raise ValueError("multiplicative_persistence() only accepts integral values")
if num < 0:
raise ValueError("multiplicative_persistence() does not accept negative values")
steps = 0
num_string = str(num)
while len(num_string) != 1:
numbers = [int(i) for i in num_string]
total = 1
for i in range(len(numbers)):
total *= numbers[i]
num_string = str(total)
steps += 1
return steps
def additive_persistence(num: int) -> int:
if not isinstance(num, int):
raise ValueError("additive_persistence() only accepts integral values")
if num < 0:
raise ValueError("additive_persistence() does not accept negative values")
steps = 0
num_string = str(num)
while len(num_string) != 1:
numbers = [int(i) for i in num_string]
total = 0
for i in range(len(numbers)):
total += numbers[i]
num_string = str(total)
steps += 1
return steps
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,4 +1,20 @@ def multiplicative_persistence(num: int) -> int:
+ """
+ Return the persistence of a given number.
+
+ https://en.wikipedia.org/wiki/Persistence_of_a_number
+
+ >>> multiplicative_persistence(217)
+ 2
+ >>> multiplicative_persistence(-1)
+ Traceback (most recent call last):
+ ...
+ ValueError: multiplicative_persistence() does not accept negative values
+ >>> multiplicative_persistence("long number")
+ Traceback (most recent call last):
+ ...
+ ValueError: multiplicative_persistence() only accepts integral values
+ """
if not isinstance(num, int):
raise ValueError("multiplicative_persistence() only accepts integral values")
@@ -22,6 +38,22 @@
def additive_persistence(num: int) -> int:
+ """
+ Return the persistence of a given number.
+
+ https://en.wikipedia.org/wiki/Persistence_of_a_number
+
+ >>> additive_persistence(199)
+ 3
+ >>> additive_persistence(-1)
+ Traceback (most recent call last):
+ ...
+ ValueError: additive_persistence() does not accept negative values
+ >>> additive_persistence("long number")
+ Traceback (most recent call last):
+ ...
+ ValueError: additive_persistence() only accepts integral values
+ """
if not isinstance(num, int):
raise ValueError("additive_persistence() only accepts integral values")
@@ -47,4 +79,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/persistence.py |
Fully document this Python code with docstrings |
from __future__ import annotations
from collections.abc import MutableSequence
class Polynomial:
def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:
if len(coefficients) != degree + 1:
raise ValueError(
"The number of coefficients should be equal to the degree + 1."
)
self.coefficients: list[float] = list(coefficients)
self.degree = degree
def __add__(self, polynomial_2: Polynomial) -> Polynomial:
if self.degree > polynomial_2.degree:
coefficients = self.coefficients[:]
for i in range(polynomial_2.degree + 1):
coefficients[i] += polynomial_2.coefficients[i]
return Polynomial(self.degree, coefficients)
else:
coefficients = polynomial_2.coefficients[:]
for i in range(self.degree + 1):
coefficients[i] += self.coefficients[i]
return Polynomial(polynomial_2.degree, coefficients)
def __sub__(self, polynomial_2: Polynomial) -> Polynomial:
return self + polynomial_2 * Polynomial(0, [-1])
def __neg__(self) -> Polynomial:
return Polynomial(self.degree, [-c for c in self.coefficients])
def __mul__(self, polynomial_2: Polynomial) -> Polynomial:
coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1)
for i in range(self.degree + 1):
for j in range(polynomial_2.degree + 1):
coefficients[i + j] += (
self.coefficients[i] * polynomial_2.coefficients[j]
)
return Polynomial(self.degree + polynomial_2.degree, coefficients)
def evaluate(self, substitution: float) -> float:
result: int | float = 0
for i in range(self.degree + 1):
result += self.coefficients[i] * (substitution**i)
return result
def __str__(self) -> str:
polynomial = ""
for i in range(self.degree, -1, -1):
if self.coefficients[i] == 0:
continue
elif self.coefficients[i] > 0:
if polynomial:
polynomial += " + "
else:
polynomial += " - "
if i == 0:
polynomial += str(abs(self.coefficients[i]))
elif i == 1:
polynomial += str(abs(self.coefficients[i])) + "x"
else:
polynomial += str(abs(self.coefficients[i])) + "x^" + str(i)
return polynomial
def __repr__(self) -> str:
return self.__str__()
def derivative(self) -> Polynomial:
coefficients: list[float] = [0] * self.degree
for i in range(self.degree):
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)
def integral(self, constant: float = 0) -> Polynomial:
coefficients: list[float] = [0] * (self.degree + 2)
coefficients[0] = constant
for i in range(self.degree + 1):
coefficients[i + 1] = self.coefficients[i] / (i + 1)
return Polynomial(self.degree + 1, coefficients)
def __eq__(self, polynomial_2: object) -> bool:
if not isinstance(polynomial_2, Polynomial):
return False
if self.degree != polynomial_2.degree:
return False
for i in range(self.degree + 1):
if self.coefficients[i] != polynomial_2.coefficients[i]:
return False
return True
def __ne__(self, polynomial_2: object) -> bool:
return not self.__eq__(polynomial_2) | --- +++ @@ -1,3 +1,11 @@+"""
+
+This module implements a single indeterminate polynomials class
+with some basic operations
+
+Reference: https://en.wikipedia.org/wiki/Polynomial
+
+"""
from __future__ import annotations
@@ -6,6 +14,15 @@
class Polynomial:
def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:
+ """
+ The coefficients should be in order of degree, from smallest to largest.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> p = Polynomial(2, [1, 2, 3, 4])
+ Traceback (most recent call last):
+ ...
+ ValueError: The number of coefficients should be equal to the degree + 1.
+
+ """
if len(coefficients) != degree + 1:
raise ValueError(
"The number of coefficients should be equal to the degree + 1."
@@ -15,6 +32,13 @@ self.degree = degree
def __add__(self, polynomial_2: Polynomial) -> Polynomial:
+ """
+ Polynomial addition
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> q = Polynomial(2, [1, 2, 3])
+ >>> p + q
+ 6x^2 + 4x + 2
+ """
if self.degree > polynomial_2.degree:
coefficients = self.coefficients[:]
@@ -28,12 +52,32 @@ return Polynomial(polynomial_2.degree, coefficients)
def __sub__(self, polynomial_2: Polynomial) -> Polynomial:
+ """
+ Polynomial subtraction
+ >>> p = Polynomial(2, [1, 2, 4])
+ >>> q = Polynomial(2, [1, 2, 3])
+ >>> p - q
+ 1x^2
+ """
return self + polynomial_2 * Polynomial(0, [-1])
def __neg__(self) -> Polynomial:
+ """
+ Polynomial negation
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> -p
+ - 3x^2 - 2x - 1
+ """
return Polynomial(self.degree, [-c for c in self.coefficients])
def __mul__(self, polynomial_2: Polynomial) -> Polynomial:
+ """
+ Polynomial multiplication
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> q = Polynomial(2, [1, 2, 3])
+ >>> p * q
+ 9x^4 + 12x^3 + 10x^2 + 4x + 1
+ """
coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1)
for i in range(self.degree + 1):
for j in range(polynomial_2.degree + 1):
@@ -44,12 +88,23 @@ return Polynomial(self.degree + polynomial_2.degree, coefficients)
def evaluate(self, substitution: float) -> float:
+ """
+ Evaluates the polynomial at x.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> p.evaluate(2)
+ 17
+ """
result: int | float = 0
for i in range(self.degree + 1):
result += self.coefficients[i] * (substitution**i)
return result
def __str__(self) -> str:
+ """
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> print(p)
+ 3x^2 + 2x + 1
+ """
polynomial = ""
for i in range(self.degree, -1, -1):
if self.coefficients[i] == 0:
@@ -70,15 +125,32 @@ return polynomial
def __repr__(self) -> str:
+ """
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> p
+ 3x^2 + 2x + 1
+ """
return self.__str__()
def derivative(self) -> Polynomial:
+ """
+ Returns the derivative of the polynomial.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> p.derivative()
+ 6x + 2
+ """
coefficients: list[float] = [0] * self.degree
for i in range(self.degree):
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)
def integral(self, constant: float = 0) -> Polynomial:
+ """
+ Returns the integral of the polynomial.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> p.integral()
+ 1.0x^3 + 1.0x^2 + 1.0x
+ """
coefficients: list[float] = [0] * (self.degree + 2)
coefficients[0] = constant
for i in range(self.degree + 1):
@@ -86,6 +158,13 @@ return Polynomial(self.degree + 1, coefficients)
def __eq__(self, polynomial_2: object) -> bool:
+ """
+ Checks if two polynomials are equal.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> q = Polynomial(2, [1, 2, 3])
+ >>> p == q
+ True
+ """
if not isinstance(polynomial_2, Polynomial):
return False
@@ -99,4 +178,11 @@ return True
def __ne__(self, polynomial_2: object) -> bool:
- return not self.__eq__(polynomial_2)+ """
+ Checks if two polynomials are not equal.
+ >>> p = Polynomial(2, [1, 2, 3])
+ >>> q = Polynomial(2, [1, 2, 3])
+ >>> p != q
+ False
+ """
+ return not self.__eq__(polynomial_2)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/polynomials/single_indeterminate_operations.py |
Create docstrings for API functions |
def solution() -> int:
return next(
iter(
[
a * b * (1000 - a - b)
for a in range(1, 999)
for b in range(a, 999)
if (a * a + b * b == (1000 - a - b) ** 2)
]
)
)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,32 @@+"""
+Project Euler Problem 9: https://projecteuler.net/problem=9
+
+Special Pythagorean triplet
+
+A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
+
+ a^2 + b^2 = c^2
+
+For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
+
+There exists exactly one Pythagorean triplet for which a + b + c = 1000.
+Find the product a*b*c.
+
+References:
+ - https://en.wikipedia.org/wiki/Pythagorean_triple
+"""
def solution() -> int:
+ """
+ Returns the product of a,b,c which are Pythagorean Triplet that satisfies
+ the following:
+ 1. a**2 + b**2 = c**2
+ 2. a + b + c = 1000
+
+ >>> solution()
+ 31875000
+ """
return next(
iter(
@@ -15,4 +41,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_009/sol3.py |
Add docstrings following best practices |
def solution(n: int = 1000) -> int:
product = -1
candidate = 0
for a in range(1, n // 3):
# Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
c = n - a - b
if c * c == (a * a + b * b):
candidate = a * b * c
product = max(product, candidate)
return product
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,35 @@+"""
+Project Euler Problem 9: https://projecteuler.net/problem=9
+
+Special Pythagorean triplet
+
+A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
+
+ a^2 + b^2 = c^2
+
+For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
+
+There exists exactly one Pythagorean triplet for which a + b + c = 1000.
+Find the product a*b*c.
+
+References:
+ - https://en.wikipedia.org/wiki/Pythagorean_triple
+"""
def solution(n: int = 1000) -> int:
+ """
+ Return the product of a,b,c which are Pythagorean Triplet that satisfies
+ the following:
+ 1. a < b < c
+ 2. a**2 + b**2 = c**2
+ 3. a + b + c = n
+
+ >>> solution(36)
+ 1620
+ >>> solution(126)
+ 66780
+ """
product = -1
candidate = 0
@@ -15,4 +44,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_009/sol2.py |
Add standardized docstrings across the file |
def count_divisors(n):
n_divisors = 1
i = 2
while i * i <= n:
multiplicity = 0
while n % i == 0:
n //= i
multiplicity += 1
n_divisors *= multiplicity + 1
i += 1
if n > 1:
n_divisors *= 2
return n_divisors
def solution():
t_num = 1
i = 1
while True:
i += 1
t_num += i
if count_divisors(t_num) > 500:
break
return t_num
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,26 @@+"""
+Highly divisible triangular numbers
+Problem 12
+The sequence of triangle numbers is generated by adding the natural numbers. So
+the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten
+terms would be:
+
+1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
+
+Let us list the factors of the first seven triangle numbers:
+
+ 1: 1
+ 3: 1,3
+ 6: 1,2,3,6
+10: 1,2,5,10
+15: 1,3,5,15
+21: 1,3,7,21
+28: 1,2,4,7,14,28
+We can see that 28 is the first triangle number to have over five divisors.
+
+What is the value of the first triangle number to have over five hundred
+divisors?
+"""
def count_divisors(n):
@@ -16,6 +39,12 @@
def solution():
+ """Returns the value of the first triangle number to have over five hundred
+ divisors.
+
+ >>> solution()
+ 76576500
+ """
t_num = 1
i = 1
@@ -30,4 +59,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_012/sol1.py |
Add documentation for all methods |
import os
def largest_product(grid):
n_columns = len(grid[0])
n_rows = len(grid)
largest = 0
lr_diag_product = 0
rl_diag_product = 0
# Check vertically, horizontally, diagonally at the same time (only works
# for nxn grid)
for i in range(n_columns):
for j in range(n_rows - 3):
vert_product = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i]
horz_product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
# Left-to-right diagonal (\) product
if i < n_columns - 3:
lr_diag_product = (
grid[i][j]
* grid[i + 1][j + 1]
* grid[i + 2][j + 2]
* grid[i + 3][j + 3]
)
# Right-to-left diagonal(/) product
if i > 2:
rl_diag_product = (
grid[i][j]
* grid[i - 1][j + 1]
* grid[i - 2][j + 2]
* grid[i - 3][j + 3]
)
max_product = max(
vert_product, horz_product, lr_diag_product, rl_diag_product
)
largest = max(largest, max_product)
return largest
def solution():
grid = []
with open(os.path.dirname(__file__) + "/grid.txt") as file:
for line in file:
grid.append(line.strip("\n").split(" "))
grid = [[int(i) for i in grid[j]] for j in range(len(grid))]
return largest_product(grid)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,28 @@+"""
+What is the greatest product of four adjacent numbers (horizontally,
+vertically, or diagonally) in this 20x20 array?
+
+08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
+49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
+81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
+52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
+22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
+24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
+32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
+67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
+24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
+21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
+78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
+16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
+86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
+19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
+04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
+88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
+04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
+20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
+20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
+01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
+"""
import os
@@ -44,6 +69,12 @@
def solution():
+ """Returns the greatest product of four adjacent numbers (horizontally,
+ vertically, or diagonally).
+
+ >>> solution()
+ 70600674
+ """
grid = []
with open(os.path.dirname(__file__) + "/grid.txt") as file:
for line in file:
@@ -55,4 +86,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_011/sol1.py |
Document helper functions with docstrings |
def triangle_number_generator():
for n in range(1, 1000000):
yield n * (n + 1) // 2
def count_divisors(n):
divisors_count = 1
i = 2
while i * i <= n:
multiplicity = 0
while n % i == 0:
n //= i
multiplicity += 1
divisors_count *= multiplicity + 1
i += 1
if n > 1:
divisors_count *= 2
return divisors_count
def solution():
return next(i for i in triangle_number_generator() if count_divisors(i) > 500)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,26 @@+"""
+Highly divisible triangular numbers
+Problem 12
+The sequence of triangle numbers is generated by adding the natural numbers. So
+the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten
+terms would be:
+
+1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
+
+Let us list the factors of the first seven triangle numbers:
+
+ 1: 1
+ 3: 1,3
+ 6: 1,2,3,6
+10: 1,2,5,10
+15: 1,3,5,15
+21: 1,3,7,21
+28: 1,2,4,7,14,28
+We can see that 28 is the first triangle number to have over five divisors.
+
+What is the value of the first triangle number to have over five hundred
+divisors?
+"""
def triangle_number_generator():
@@ -21,8 +44,14 @@
def solution():
+ """Returns the value of the first triangle number to have over five hundred
+ divisors.
+
+ >>> solution()
+ 76576500
+ """
return next(i for i in triangle_number_generator() if count_divisors(i) > 500)
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_012/sol2.py |
Add docstrings for production code |
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(n: int = 2000000) -> int:
return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,38 @@+"""
+Project Euler Problem 10: https://projecteuler.net/problem=10
+
+Summation of primes
+
+The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
+
+Find the sum of all the primes below two million.
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number num (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,9 +49,21 @@
def solution(n: int = 2000000) -> int:
+ """
+ Returns the sum of all the primes below n.
+
+ >>> solution(1000)
+ 76127
+ >>> solution(5000)
+ 1548136
+ >>> solution(10000)
+ 5736396
+ >>> solution(7)
+ 10
+ """
return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_010/sol1.py |
Provide clean and structured docstrings |
def solution() -> int:
for a in range(300):
for b in range(a + 1, 400):
for c in range(b + 1, 500):
if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2):
return a * b * c
return -1
def solution_fast() -> int:
for a in range(300):
for b in range(400):
c = 1000 - a - b
if a < b < c and (a**2) + (b**2) == (c**2):
return a * b * c
return -1
def benchmark() -> None:
import timeit
print(
timeit.timeit("solution()", setup="from __main__ import solution", number=1000)
)
print(
timeit.timeit(
"solution_fast()", setup="from __main__ import solution_fast", number=1000
)
)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,33 @@+"""
+Project Euler Problem 9: https://projecteuler.net/problem=9
+
+Special Pythagorean triplet
+
+A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
+
+ a^2 + b^2 = c^2
+
+For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
+
+There exists exactly one Pythagorean triplet for which a + b + c = 1000.
+Find the product a*b*c.
+
+References:
+ - https://en.wikipedia.org/wiki/Pythagorean_triple
+"""
def solution() -> int:
+ """
+ Returns the product of a,b,c which are Pythagorean Triplet that satisfies
+ the following:
+ 1. a < b < c
+ 2. a**2 + b**2 = c**2
+ 3. a + b + c = 1000
+
+ >>> solution()
+ 31875000
+ """
for a in range(300):
for b in range(a + 1, 400):
@@ -12,6 +39,16 @@
def solution_fast() -> int:
+ """
+ Returns the product of a,b,c which are Pythagorean Triplet that satisfies
+ the following:
+ 1. a < b < c
+ 2. a**2 + b**2 = c**2
+ 3. a + b + c = 1000
+
+ >>> solution_fast()
+ 31875000
+ """
for a in range(300):
for b in range(400):
@@ -23,6 +60,9 @@
def benchmark() -> None:
+ """
+ Benchmark code comparing two different version function.
+ """
import timeit
print(
@@ -36,4 +76,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_009/sol1.py |
Generate NumPy-style docstrings |
def solution(n: int = 4000000) -> int:
if n <= 1:
return 0
a = 0
b = 2
count = 0
while 4 * b + a <= n:
a, b = b, 4 * b + a
count += a
return count + b
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,37 @@+"""
+Project Euler Problem 2: https://projecteuler.net/problem=2
+
+Even Fibonacci Numbers
+
+Each new term in the Fibonacci sequence is generated by adding the previous
+two terms. By starting with 1 and 2, the first 10 terms will be:
+
+1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+By considering the terms in the Fibonacci sequence whose values do not exceed
+four million, find the sum of the even-valued terms.
+
+References:
+ - https://en.wikipedia.org/wiki/Fibonacci_number
+"""
def solution(n: int = 4000000) -> int:
+ """
+ Returns the sum of all even fibonacci sequence elements that are lower
+ or equal to n.
+
+ >>> solution(10)
+ 10
+ >>> solution(15)
+ 10
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 0
+ >>> solution(34)
+ 44
+ """
if n <= 1:
return 0
@@ -14,4 +45,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_002/sol3.py |
Create Google-style docstrings for my code |
def solution(n: int = 2000000) -> int:
primality_list = [0 for i in range(n + 1)]
primality_list[0] = 1
primality_list[1] = 1
for i in range(2, int(n**0.5) + 1):
if primality_list[i] == 0:
for j in range(i * i, n + 1, i):
primality_list[j] = 1
sum_of_primes = 0
for i in range(n):
if primality_list[i] == 0:
sum_of_primes += i
return sum_of_primes
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,46 @@+"""
+Project Euler Problem 10: https://projecteuler.net/problem=10
+
+Summation of primes
+
+The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
+
+Find the sum of all the primes below two million.
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+ - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
+"""
def solution(n: int = 2000000) -> int:
+ """
+ Returns the sum of all the primes below n using Sieve of Eratosthenes:
+
+ The sieve of Eratosthenes is one of the most efficient ways to find all primes
+ smaller than n when n is smaller than 10 million. Only for positive numbers.
+
+ >>> solution(1000)
+ 76127
+ >>> solution(5000)
+ 1548136
+ >>> solution(10000)
+ 5736396
+ >>> solution(7)
+ 10
+ >>> solution(7.1) # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ TypeError: 'float' object cannot be interpreted as an integer
+ >>> solution(-7) # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ IndexError: list assignment index out of range
+ >>> solution("seven") # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ TypeError: can only concatenate str (not "int") to str
+ """
primality_list = [0 for i in range(n + 1)]
primality_list[0] = 1
@@ -18,4 +58,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_010/sol3.py |
Add docstrings to meet PEP guidelines |
import math
from collections.abc import Iterator
from itertools import takewhile
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def prime_generator() -> Iterator[int]:
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,3 +1,15 @@+"""
+Project Euler Problem 10: https://projecteuler.net/problem=10
+
+Summation of primes
+
+The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
+
+Find the sum of all the primes below two million.
+
+References:
+ - https://en.wikipedia.org/wiki/Prime_number
+"""
import math
from collections.abc import Iterator
@@ -5,6 +17,24 @@
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number num (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -21,6 +51,9 @@
def prime_generator() -> Iterator[int]:
+ """
+ Generate a list sequence of prime numbers
+ """
num = 2
while True:
@@ -30,9 +63,21 @@
def solution(n: int = 2000000) -> int:
+ """
+ Returns the sum of all the primes below n.
+
+ >>> solution(1000)
+ 76127
+ >>> solution(5000)
+ 1548136
+ >>> solution(10000)
+ 5736396
+ >>> solution(7)
+ 10
+ """
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_010/sol2.py |
Write docstrings for algorithm functions |
import os
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]
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,12 +1,26 @@+"""
+Problem 13: https://projecteuler.net/problem=13
+
+Problem Statement:
+Work out the first ten digits of the sum of the following one-hundred 50-digit
+numbers.
+"""
import os
def solution():
+ """
+ Returns the first ten digits of the sum of the array elements
+ from the file num.txt
+
+ >>> solution()
+ '5537376230'
+ """
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]
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_013/sol1.py |
Add docstrings that explain purpose and usage |
from __future__ import annotations
COLLATZ_SEQUENCE_LENGTHS = {1: 1}
def collatz_sequence_length(n: int) -> int:
if n in COLLATZ_SEQUENCE_LENGTHS:
return COLLATZ_SEQUENCE_LENGTHS[n]
next_n = n // 2 if n % 2 == 0 else 3 * n + 1
sequence_length = collatz_sequence_length(next_n) + 1
COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
return sequence_length
def solution(n: int = 1000000) -> int:
result = max((collatz_sequence_length(i), i) for i in range(1, n))
return result[1]
if __name__ == "__main__":
print(solution(int(input().strip()))) | --- +++ @@ -1,3 +1,30 @@+"""
+Problem 14: https://projecteuler.net/problem=14
+
+Collatz conjecture: start with any positive integer n. Next term obtained from
+the previous term as follows:
+
+If the previous term is even, the next term is one half the previous term.
+If the previous term is odd, the next term is 3 times the previous term plus 1.
+The conjecture states the sequence will always reach 1 regardless of starting
+n.
+
+Problem Statement:
+The following iterative sequence is defined for the set of positive integers:
+
+ n → n/2 (n is even)
+ n → 3n + 1 (n is odd)
+
+Using the rule above and starting with 13, we generate the following sequence:
+
+ 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
+
+It can be seen that this sequence (starting at 13 and finishing at 1) contains
+10 terms. Although it has not been proved yet (Collatz Problem), it is thought
+that all starting numbers finish at 1.
+
+Which starting number, under one million, produces the longest chain?
+"""
from __future__ import annotations
@@ -5,6 +32,7 @@
def collatz_sequence_length(n: int) -> int:
+ """Returns the Collatz sequence length for n."""
if n in COLLATZ_SEQUENCE_LENGTHS:
return COLLATZ_SEQUENCE_LENGTHS[n]
next_n = n // 2 if n % 2 == 0 else 3 * n + 1
@@ -14,10 +42,21 @@
def solution(n: int = 1000000) -> int:
+ """Returns the number under n that generates the longest Collatz sequence.
+
+ >>> solution(1000000)
+ 837799
+ >>> solution(200)
+ 171
+ >>> solution(5000)
+ 3711
+ >>> solution(15000)
+ 13255
+ """
result = max((collatz_sequence_length(i), i) for i in range(1, n))
return result[1]
if __name__ == "__main__":
- print(solution(int(input().strip())))+ print(solution(int(input().strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_014/sol2.py |
Add docstrings for utility scripts |
def solution(n: int = 1000000) -> int:
largest_number = 1
pre_counter = 1
counters = {1: 1}
for input1 in range(2, n):
counter = 0
number = input1
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
number = (3 * number) + 1
counter += 1
if input1 not in counters:
counters[input1] = counter
if counter > pre_counter:
largest_number = input1
pre_counter = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip()))) | --- +++ @@ -1,6 +1,39 @@+"""
+Problem 14: https://projecteuler.net/problem=14
+
+Problem Statement:
+The following iterative sequence is defined for the set of positive integers:
+
+ n → n/2 (n is even)
+ n → 3n + 1 (n is odd)
+
+Using the rule above and starting with 13, we generate the following sequence:
+
+ 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
+
+It can be seen that this sequence (starting at 13 and finishing at 1) contains
+10 terms. Although it has not been proved yet (Collatz Problem), it is thought
+that all starting numbers finish at 1.
+
+Which starting number, under one million, produces the longest chain?
+"""
def solution(n: int = 1000000) -> int:
+ """Returns the number under n that generates the longest sequence using the
+ formula:
+ n → n/2 (n is even)
+ n → 3n + 1 (n is odd)
+
+ >>> solution(1000000)
+ 837799
+ >>> solution(200)
+ 171
+ >>> solution(5000)
+ 3711
+ >>> solution(15000)
+ 13255
+ """
largest_number = 1
pre_counter = 1
counters = {1: 1}
@@ -30,4 +63,4 @@
if __name__ == "__main__":
- print(solution(int(input().strip())))+ print(solution(int(input().strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_014/sol1.py |
Replace inline comments with docstrings |
def solution(n: int = 20) -> int:
counts = [[1 for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
counts[i][j] = counts[i - 1][j] + counts[i][j - 1]
return counts[n][n]
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,23 @@+"""
+Problem 15: https://projecteuler.net/problem=15
+
+Starting in the top left corner of a 2x2 grid, and only being able to move to
+the right and down, there are exactly 6 routes to the bottom right corner.
+How many such routes are there through a 20x20 grid?
+"""
def solution(n: int = 20) -> int:
+ """
+ Solve by explicitly counting the paths with dynamic programming.
+
+ >>> solution(6)
+ 924
+ >>> solution(2)
+ 6
+ >>> solution(1)
+ 2
+ """
counts = [[1 for _ in range(n + 1)] for _ in range(n + 1)]
@@ -12,4 +29,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_015/sol2.py |
Add docstrings including usage examples |
from math import factorial
def solution(n: int = 20) -> int:
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
k = n // 2
return int(factorial(n) / (factorial(k) * factorial(n - k)))
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
n = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number.") | --- +++ @@ -1,8 +1,30 @@+"""
+Problem 15: https://projecteuler.net/problem=15
+
+Starting in the top left corner of a 2x2 grid, and only being able to move to
+the right and down, there are exactly 6 routes to the bottom right corner.
+How many such routes are there through a 20x20 grid?
+"""
from math import factorial
def solution(n: int = 20) -> int:
+ """
+ Returns the number of paths possible in a n x n grid starting at top left
+ corner going to bottom right corner and being able to move right and down
+ only.
+ >>> solution(25)
+ 126410606437752
+ >>> solution(23)
+ 8233430727600
+ >>> solution(20)
+ 137846528820
+ >>> solution(15)
+ 155117520
+ >>> solution(1)
+ 2
+ """
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
k = n // 2
@@ -20,4 +42,4 @@ n = int(sys.argv[1])
print(solution(n))
except ValueError:
- print("Invalid entry - please enter a number.")+ print("Invalid entry - please enter a number.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_015/sol1.py |
Write docstrings describing each step |
def solution(power: int = 1000) -> int:
num = 2**power
string_num = str(num)
list_num = list(string_num)
sum_of_num = 0
for i in list_num:
sum_of_num += int(i)
return sum_of_num
if __name__ == "__main__":
power = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2**power)
result = solution(power)
print("Sum of the digits is: ", result) | --- +++ @@ -1,6 +1,23 @@+"""
+Problem 16: https://projecteuler.net/problem=16
+
+2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
+
+What is the sum of the digits of the number 2^1000?
+"""
def solution(power: int = 1000) -> int:
+ """Returns the sum of the digits of the number 2^power.
+ >>> solution(1000)
+ 1366
+ >>> solution(50)
+ 76
+ >>> solution(20)
+ 31
+ >>> solution(15)
+ 26
+ """
num = 2**power
string_num = str(num)
list_num = list(string_num)
@@ -16,4 +33,4 @@ power = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2**power)
result = solution(power)
- print("Sum of the digits is: ", result)+ print("Sum of the digits is: ", result)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_016/sol1.py |
Add structured docstrings to improve clarity |
import os
def solution():
with open(os.path.dirname(__file__) + "/grid.txt") as f:
grid = []
for _ in range(20):
grid.append([int(x) for x in f.readline().split()])
maximum = 0
# right
for i in range(20):
for j in range(17):
temp = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
maximum = max(maximum, temp)
# down
for i in range(17):
for j in range(20):
temp = grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j]
maximum = max(maximum, temp)
# diagonal 1
for i in range(17):
for j in range(17):
temp = (
grid[i][j]
* grid[i + 1][j + 1]
* grid[i + 2][j + 2]
* grid[i + 3][j + 3]
)
maximum = max(maximum, temp)
# diagonal 2
for i in range(17):
for j in range(3, 20):
temp = (
grid[i][j]
* grid[i + 1][j - 1]
* grid[i + 2][j - 2]
* grid[i + 3][j - 3]
)
maximum = max(maximum, temp)
return maximum
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,39 @@+"""
+What is the greatest product of four adjacent numbers (horizontally,
+vertically, or diagonally) in this 20x20 array?
+
+08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
+49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
+81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
+52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
+22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
+24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
+32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
+67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
+24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
+21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
+78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
+16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
+86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
+19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
+04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
+88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
+04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
+20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
+20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
+01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
+"""
import os
def solution():
+ """Returns the greatest product of four adjacent numbers (horizontally,
+ vertically, or diagonally).
+
+ >>> solution()
+ 70600674
+ """
with open(os.path.dirname(__file__) + "/grid.txt") as f:
grid = []
for _ in range(20):
@@ -47,4 +78,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_011/sol2.py |
Generate consistent docstrings |
def solution(power: int = 1000) -> int:
n = 2**power
r = 0
while n:
r, n = r + n % 10, n // 10
return r
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | --- +++ @@ -1,6 +1,24 @@+"""
+Problem 16: https://projecteuler.net/problem=16
+
+2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
+
+What is the sum of the digits of the number 2^1000?
+"""
def solution(power: int = 1000) -> int:
+ """Returns the sum of the digits of the number 2^power.
+
+ >>> solution(1000)
+ 1366
+ >>> solution(50)
+ 76
+ >>> solution(20)
+ 31
+ >>> solution(15)
+ 26
+ """
n = 2**power
r = 0
while n:
@@ -9,4 +27,4 @@
if __name__ == "__main__":
- print(solution(int(str(input()).strip())))+ print(solution(int(str(input()).strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_016/sol2.py |
Generate consistent docstrings |
import os
def solution():
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number2 = a[i - 1][j - 1] if j > 0 else 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,44 @@+"""
+By starting at the top of the triangle below and moving to adjacent numbers on
+the row below, the maximum total from top to bottom is 23.
+
+3
+7 4
+2 4 6
+8 5 9 3
+
+That is, 3 + 7 + 4 + 9 = 23.
+
+Find the maximum total from top to bottom of the triangle below:
+
+75
+95 64
+17 47 82
+18 35 87 10
+20 04 82 47 65
+19 01 23 75 03 34
+88 02 77 73 07 63 67
+99 65 04 28 06 16 70 92
+41 41 26 56 83 40 80 70 33
+41 48 72 33 47 32 37 16 94 29
+53 71 44 65 25 43 91 52 97 51 14
+70 11 33 28 77 73 17 78 39 68 17 57
+91 71 52 38 17 14 91 43 58 50 27 29 48
+63 66 04 68 89 53 67 30 73 16 69 87 40 31
+04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
+"""
import os
def solution():
+ """
+ Finds the maximum total in a triangle as described by the problem statement
+ above.
+
+ >>> solution()
+ 1074
+ """
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
@@ -20,4 +56,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_018/solution.py |
Write docstrings for utility functions |
from math import factorial
def solution(num: int = 100) -> int:
return sum(int(x) for x in str(factorial(num)))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip()))) | --- +++ @@ -1,10 +1,36 @@+"""
+Problem 20: https://projecteuler.net/problem=20
+
+n! means n x (n - 1) x ... x 3 x 2 x 1
+
+For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
+and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
+
+Find the sum of the digits in the number 100!
+"""
from math import factorial
def solution(num: int = 100) -> int:
+ """Returns the sum of the digits in the factorial of num
+ >>> solution(100)
+ 648
+ >>> solution(50)
+ 216
+ >>> solution(10)
+ 27
+ >>> solution(5)
+ 3
+ >>> solution(3)
+ 6
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 1
+ """
return sum(int(x) for x in str(factorial(num)))
if __name__ == "__main__":
- print(solution(int(input("Enter the Number: ").strip())))+ print(solution(int(input("Enter the Number: ").strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_020/sol2.py |
Document all public functions with docstrings |
def factorial(num: int) -> int:
fact = 1
for i in range(1, num + 1):
fact *= i
return fact
def split_and_add(number: int) -> int:
sum_of_digits = 0
while number > 0:
last_digit = number % 10
sum_of_digits += last_digit
number = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def solution(num: int = 100) -> int:
nfact = factorial(num)
result = split_and_add(nfact)
return result
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip()))) | --- +++ @@ -1,6 +1,17 @@+"""
+Problem 20: https://projecteuler.net/problem=20
+
+n! means n x (n - 1) x ... x 3 x 2 x 1
+
+For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
+and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
+
+Find the sum of the digits in the number 100!
+"""
def factorial(num: int) -> int:
+ """Find the factorial of a given number n"""
fact = 1
for i in range(1, num + 1):
fact *= i
@@ -8,6 +19,7 @@
def split_and_add(number: int) -> int:
+ """Split number digits and add them."""
sum_of_digits = 0
while number > 0:
last_digit = number % 10
@@ -17,10 +29,26 @@
def solution(num: int = 100) -> int:
+ """Returns the sum of the digits in the factorial of num
+ >>> solution(100)
+ 648
+ >>> solution(50)
+ 216
+ >>> solution(10)
+ 27
+ >>> solution(5)
+ 3
+ >>> solution(3)
+ 6
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 1
+ """
nfact = factorial(num)
result = split_and_add(nfact)
return result
if __name__ == "__main__":
- print(solution(int(input("Enter the Number: ").strip())))+ print(solution(int(input("Enter the Number: ").strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_020/sol1.py |
Add docstrings with type hints explained |
def solution():
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = 6
month = 1
year = 1901
sundays = 0
while year < 2001:
day += 7
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
if day > days_per_month[month - 1] and month != 2:
month += 1
day = day - days_per_month[month - 2]
elif day > 29 and month == 2:
month += 1
day = day - 29
elif day > days_per_month[month - 1]:
month += 1
day = day - days_per_month[month - 2]
if month > 12:
year += 1
month = 1
if year < 2001 and day == 1:
sundays += 1
return sundays
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,33 @@+"""
+Counting Sundays
+Problem 19
+
+You are given the following information, but you may prefer to do some research
+for yourself.
+
+1 Jan 1900 was a Monday.
+Thirty days has September,
+April, June and November.
+All the rest have thirty-one,
+Saving February alone,
+Which has twenty-eight, rain or shine.
+And on leap years, twenty-nine.
+
+A leap year occurs on any year evenly divisible by 4, but not on a century
+unless it is divisible by 400.
+
+How many Sundays fell on the first of the month during the twentieth century
+(1 Jan 1901 to 31 Dec 2000)?
+"""
def solution():
+ """Returns the number of mondays that fall on the first of the month during
+ the twentieth century (1 Jan 1901 to 31 Dec 2000)?
+
+ >>> solution()
+ 171
+ """
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = 6
@@ -33,4 +60,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_019/sol1.py |
Generate consistent docstrings |
def solution(n: int = 1000) -> int:
# number of letters in zero, one, two, ..., nineteen (0 for zero since it's
# never said aloud)
ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
# number of letters in twenty, thirty, ..., ninety (0 for numbers less than
# 20 due to inconsistency in teens)
tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]
count = 0
for i in range(1, n + 1):
if i < 1000:
if i >= 100:
# add number of letters for "n hundred"
count += ones_counts[i // 100] + 7
if i % 100 != 0:
# add number of letters for "and" if number is not multiple
# of 100
count += 3
if 0 < i % 100 < 20:
# add number of letters for one, two, three, ..., nineteen
# (could be combined with below if not for inconsistency in
# teens)
count += ones_counts[i % 100]
else:
# add number of letters for twenty, twenty one, ..., ninety
# nine
count += ones_counts[i % 10]
count += tens_counts[(i % 100 - i % 10) // 10]
else:
count += ones_counts[i // 1000] + 8
return count
if __name__ == "__main__":
print(solution(int(input().strip()))) | --- +++ @@ -1,6 +1,29 @@+"""
+Number letter counts
+Problem 17: https://projecteuler.net/problem=17
+
+If the numbers 1 to 5 are written out in words: one, two, three, four, five,
+then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
+
+If all the numbers from 1 to 1000 (one thousand) inclusive were written out in
+words, how many letters would be used?
+
+
+NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
+forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20
+letters. The use of "and" when writing out numbers is in compliance withBritish
+usage.
+"""
def solution(n: int = 1000) -> int:
+ """Returns the number of letters used to write all numbers from 1 to n.
+ where n is lower or equals to 1000.
+ >>> solution(1000)
+ 21124
+ >>> solution(5)
+ 19
+ """
# number of letters in zero, one, two, ..., nineteen (0 for zero since it's
# never said aloud)
ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
@@ -37,4 +60,4 @@
if __name__ == "__main__":
- print(solution(int(input().strip())))+ print(solution(int(input().strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_017/sol1.py |
Add professional docstrings to my codebase |
def solution(num: int = 100) -> int:
fact = 1
result = 0
for i in range(1, num + 1):
fact *= i
for j in str(fact):
result += int(j)
return result
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip()))) | --- +++ @@ -1,6 +1,32 @@+"""
+Problem 20: https://projecteuler.net/problem=20
+
+n! means n x (n - 1) x ... x 3 x 2 x 1
+
+For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
+and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
+
+Find the sum of the digits in the number 100!
+"""
def solution(num: int = 100) -> int:
+ """Returns the sum of the digits in the factorial of num
+ >>> solution(100)
+ 648
+ >>> solution(50)
+ 216
+ >>> solution(10)
+ 27
+ >>> solution(5)
+ 3
+ >>> solution(3)
+ 6
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 1
+ """
fact = 1
result = 0
for i in range(1, num + 1):
@@ -13,4 +39,4 @@
if __name__ == "__main__":
- print(solution(int(input("Enter the Number: ").strip())))+ print(solution(int(input("Enter the Number: ").strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_020/sol4.py |
Document this code for team use |
from math import sqrt
def sum_of_divisors(n: int) -> int:
total = 0
for i in range(1, int(sqrt(n) + 1)):
if n % i == 0 and i != sqrt(n):
total += i + n // i
elif i == sqrt(n):
total += i
return total - n
def solution(n: int = 10000) -> int:
total = sum(
i
for i in range(1, n)
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
)
return total
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | --- +++ @@ -1,3 +1,18 @@+"""
+Amicable Numbers
+Problem 21
+
+Let d(n) be defined as the sum of proper divisors of n (numbers less than n
+which divide evenly into n).
+If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and
+each of a and b are called amicable numbers.
+
+For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
+and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
+142; so d(284) = 220.
+
+Evaluate the sum of all the amicable numbers under 10000.
+"""
from math import sqrt
@@ -13,6 +28,19 @@
def solution(n: int = 10000) -> int:
+ """Returns the sum of all the amicable numbers under n.
+
+ >>> solution(10000)
+ 31626
+ >>> solution(5000)
+ 8442
+ >>> solution(1000)
+ 504
+ >>> solution(100)
+ 0
+ >>> solution(50)
+ 0
+ """
total = sum(
i
for i in range(1, n)
@@ -22,4 +50,4 @@
if __name__ == "__main__":
- print(solution(int(str(input()).strip())))+ print(solution(int(str(input()).strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_021/sol1.py |
Generate docstrings for exported functions |
def solution(limit=28123):
sum_divs = [1] * (limit + 1)
for i in range(2, int(limit**0.5) + 1):
sum_divs[i * i] += i
for k in range(i + 1, limit // i + 1):
sum_divs[k * i] += k + i
abundants = set()
res = 0
for n in range(1, limit + 1):
if sum_divs[n] > n:
abundants.add(n)
if not any((n - a in abundants) for a in abundants):
res += n
return res
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,33 @@+"""
+A perfect number is a number for which the sum of its proper divisors is exactly
+equal to the number. For example, the sum of the proper divisors of 28 would be
+1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
+
+A number n is called deficient if the sum of its proper divisors is less than n
+and it is called abundant if this sum exceeds n.
+
+As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
+number that can be written as the sum of two abundant numbers is 24. By
+mathematical analysis, it can be shown that all integers greater than 28123
+can be written as the sum of two abundant numbers. However, this upper limit
+cannot be reduced any further by analysis even though it is known that the
+greatest number that cannot be expressed as the sum of two abundant numbers
+is less than this limit.
+
+Find the sum of all the positive integers which cannot be written as the sum
+of two abundant numbers.
+"""
def solution(limit=28123):
+ """
+ Finds the sum of all the positive integers which cannot be written as
+ the sum of two abundant numbers
+ as described by the statement above.
+
+ >>> solution()
+ 4179871
+ """
sum_divs = [1] * (limit + 1)
for i in range(2, int(limit**0.5) + 1):
@@ -22,4 +49,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_023/sol1.py |
Generate missing documentation strings |
import os
def solution():
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
names = str(file.readlines()[0])
names = names.replace('"', "").split(",")
names.sort()
name_score = 0
total_score = 0
for i, name in enumerate(names):
for letter in name:
name_score += ord(letter) - 64
total_score += (i + 1) * name_score
name_score = 0
return total_score
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,29 @@+"""
+Name scores
+Problem 22
+
+Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
+containing over five-thousand first names, begin by sorting it into
+alphabetical order. Then working out the alphabetical value for each name,
+multiply this value by its alphabetical position in the list to obtain a name
+score.
+
+For example, when the list is sorted into alphabetical order, COLIN, which is
+worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
+obtain a score of 938 x 53 = 49714.
+
+What is the total of all the name scores in the file?
+"""
import os
def solution():
+ """Returns the total of all the name scores in the file.
+
+ >>> solution()
+ 871198282
+ """
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
names = str(file.readlines()[0])
names = names.replace('"', "").split(",")
@@ -22,4 +43,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_022/sol1.py |
Generate descriptive docstrings automatically |
from math import factorial
def solution(num: int = 100) -> int:
return sum(map(int, str(factorial(num))))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip()))) | --- +++ @@ -1,10 +1,42 @@+"""
+Problem 20: https://projecteuler.net/problem=20
+
+n! means n x (n - 1) x ... x 3 x 2 x 1
+
+For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
+and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
+
+Find the sum of the digits in the number 100!
+"""
from math import factorial
def solution(num: int = 100) -> int:
+ """Returns the sum of the digits in the factorial of num
+ >>> solution(1000)
+ 10539
+ >>> solution(200)
+ 1404
+ >>> solution(100)
+ 648
+ >>> solution(50)
+ 216
+ >>> solution(10)
+ 27
+ >>> solution(5)
+ 3
+ >>> solution(3)
+ 6
+ >>> solution(2)
+ 2
+ >>> solution(1)
+ 1
+ >>> solution(0)
+ 1
+ """
return sum(map(int, str(factorial(num))))
if __name__ == "__main__":
- print(solution(int(input("Enter the Number: ").strip())))+ print(solution(int(input("Enter the Number: ").strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_020/sol3.py |
Add standardized docstrings across the file |
from itertools import permutations
def solution():
result = list(map("".join, permutations("0123456789")))
return result[999999]
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,11 +1,28 @@+"""
+A permutation is an ordered arrangement of objects. For example, 3124 is one
+possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
+are listed numerically or alphabetically, we call it lexicographic order. The
+lexicographic permutations of 0, 1 and 2 are:
+
+ 012 021 102 120 201 210
+
+What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5,
+6, 7, 8 and 9?
+"""
from itertools import permutations
def solution():
+ """Returns the millionth lexicographic permutation of the digits 0, 1, 2,
+ 3, 4, 5, 6, 7, 8 and 9.
+
+ >>> solution()
+ '2783915460'
+ """
result = list(map("".join, permutations("0123456789")))
return result[999999]
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_024/sol1.py |
Add inline docstrings for readability |
import os
def solution():
total_sum = 0
temp_sum = 0
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
name = str(file.readlines()[0])
name = name.replace('"', "").split(",")
name.sort()
for i in range(len(name)):
for j in name[i]:
temp_sum += ord(j) - ord("A") + 1
total_sum += (i + 1) * temp_sum
temp_sum = 0
return total_sum
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,29 @@+"""
+Name scores
+Problem 22
+
+Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
+containing over five-thousand first names, begin by sorting it into
+alphabetical order. Then working out the alphabetical value for each name,
+multiply this value by its alphabetical position in the list to obtain a name
+score.
+
+For example, when the list is sorted into alphabetical order, COLIN, which is
+worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
+obtain a score of 938 x 53 = 49714.
+
+What is the total of all the name scores in the file?
+"""
import os
def solution():
+ """Returns the total of all the name scores in the file.
+
+ >>> solution()
+ 871198282
+ """
total_sum = 0
temp_sum = 0
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
@@ -19,4 +40,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_022/sol2.py |
Write docstrings for algorithm functions |
def fibonacci(n: int) -> int:
if n == 1 or not isinstance(n, int):
return 0
elif n == 2:
return 1
else:
sequence = [0, 1]
for i in range(2, n + 1):
sequence.append(sequence[i - 1] + sequence[i - 2])
return sequence[n]
def fibonacci_digits_index(n: int) -> int:
digits = 0
index = 2
while digits < n:
index += 1
digits = len(str(fibonacci(index)))
return index
def solution(n: int = 1000) -> int:
return fibonacci_digits_index(n)
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | --- +++ @@ -1,6 +1,48 @@+"""
+The Fibonacci sequence is defined by the recurrence relation:
+
+ Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
+
+Hence the first 12 terms will be:
+
+ F1 = 1
+ F2 = 1
+ F3 = 2
+ F4 = 3
+ F5 = 5
+ F6 = 8
+ F7 = 13
+ F8 = 21
+ F9 = 34
+ F10 = 55
+ F11 = 89
+ F12 = 144
+
+The 12th term, F12, is the first term to contain three digits.
+
+What is the index of the first term in the Fibonacci sequence to contain 1000
+digits?
+"""
def fibonacci(n: int) -> int:
+ """
+ Computes the Fibonacci number for input n by iterating through n numbers
+ and creating an array of ints using the Fibonacci formula.
+ Returns the nth element of the array.
+
+ >>> fibonacci(2)
+ 1
+ >>> fibonacci(3)
+ 2
+ >>> fibonacci(5)
+ 5
+ >>> fibonacci(10)
+ 55
+ >>> fibonacci(12)
+ 144
+
+ """
if n == 1 or not isinstance(n, int):
return 0
elif n == 2:
@@ -14,6 +56,20 @@
def fibonacci_digits_index(n: int) -> int:
+ """
+ Computes incrementing Fibonacci numbers starting from 3 until the length
+ of the resulting Fibonacci result is the input value n. Returns the term
+ of the Fibonacci sequence where this occurs.
+
+ >>> fibonacci_digits_index(1000)
+ 4782
+ >>> fibonacci_digits_index(100)
+ 476
+ >>> fibonacci_digits_index(50)
+ 237
+ >>> fibonacci_digits_index(3)
+ 12
+ """
digits = 0
index = 2
@@ -25,8 +81,21 @@
def solution(n: int = 1000) -> int:
+ """
+ Returns the index of the first term in the Fibonacci sequence to contain
+ n digits.
+
+ >>> solution(1000)
+ 4782
+ >>> solution(100)
+ 476
+ >>> solution(50)
+ 237
+ >>> solution(3)
+ 12
+ """
return fibonacci_digits_index(n)
if __name__ == "__main__":
- print(solution(int(str(input()).strip())))+ print(solution(int(str(input()).strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_025/sol1.py |
Write docstrings for algorithm functions |
def solution(n: int = 1000) -> int:
f1, f2 = 1, 1
index = 2
while True:
i = 0
f = f1 + f2
f1, f2 = f2, f
index += 1
for _ in str(f):
i += 1
if i == n:
break
return index
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | --- +++ @@ -1,6 +1,43 @@+"""
+The Fibonacci sequence is defined by the recurrence relation:
+
+ Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
+
+Hence the first 12 terms will be:
+
+ F1 = 1
+ F2 = 1
+ F3 = 2
+ F4 = 3
+ F5 = 5
+ F6 = 8
+ F7 = 13
+ F8 = 21
+ F9 = 34
+ F10 = 55
+ F11 = 89
+ F12 = 144
+
+The 12th term, F12, is the first term to contain three digits.
+
+What is the index of the first term in the Fibonacci sequence to contain 1000
+digits?
+"""
def solution(n: int = 1000) -> int:
+ """Returns the index of the first term in the Fibonacci sequence to contain
+ n digits.
+
+ >>> solution(1000)
+ 4782
+ >>> solution(100)
+ 476
+ >>> solution(50)
+ 237
+ >>> solution(3)
+ 12
+ """
f1, f2 = 1, 1
index = 2
while True:
@@ -16,4 +53,4 @@
if __name__ == "__main__":
- print(solution(int(str(input()).strip())))+ print(solution(int(str(input()).strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_025/sol3.py |
Add docstrings to incomplete code |
from collections.abc import Generator
def fibonacci_generator() -> Generator[int]:
a, b = 0, 1
while True:
a, b = b, a + b
yield b
def solution(n: int = 1000) -> int:
answer = 1
gen = fibonacci_generator()
while len(str(next(gen))) < n:
answer += 1
return answer + 1
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | --- +++ @@ -1,8 +1,48 @@+"""
+The Fibonacci sequence is defined by the recurrence relation:
+
+ Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
+
+Hence the first 12 terms will be:
+
+ F1 = 1
+ F2 = 1
+ F3 = 2
+ F4 = 3
+ F5 = 5
+ F6 = 8
+ F7 = 13
+ F8 = 21
+ F9 = 34
+ F10 = 55
+ F11 = 89
+ F12 = 144
+
+The 12th term, F12, is the first term to contain three digits.
+
+What is the index of the first term in the Fibonacci sequence to contain 1000
+digits?
+"""
from collections.abc import Generator
def fibonacci_generator() -> Generator[int]:
+ """
+ A generator that produces numbers in the Fibonacci sequence
+
+ >>> generator = fibonacci_generator()
+ >>> next(generator)
+ 1
+ >>> next(generator)
+ 2
+ >>> next(generator)
+ 3
+ >>> next(generator)
+ 5
+ >>> next(generator)
+ 8
+ """
a, b = 0, 1
while True:
a, b = b, a + b
@@ -10,6 +50,18 @@
def solution(n: int = 1000) -> int:
+ """Returns the index of the first term in the Fibonacci sequence to contain
+ n digits.
+
+ >>> solution(1000)
+ 4782
+ >>> solution(100)
+ 476
+ >>> solution(50)
+ 237
+ >>> solution(3)
+ 12
+ """
answer = 1
gen = fibonacci_generator()
while len(str(next(gen))) < n:
@@ -18,4 +70,4 @@
if __name__ == "__main__":
- print(solution(int(str(input()).strip())))+ print(solution(int(str(input()).strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_025/sol2.py |
Add detailed docstrings explaining each function |
from math import sqrt
from maths.greatest_common_divisor import gcd_by_iterative
def is_prime(number: int) -> bool:
# precondition
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)
status = True
# 0 and 1 are none primes.
if number <= 1:
status = False
for divisor in range(2, round(sqrt(number)) + 1):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
status = False
break
# precondition
assert isinstance(status, bool), "'status' must been from type bool"
return status
# ------------------------------------------
def sieve_er(n):
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
begin_list = list(range(2, n + 1))
ans = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(begin_list)):
for j in range(i + 1, len(begin_list)):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
begin_list[j] = 0
# filters actual prime numbers.
ans = [x for x in begin_list if x != 0]
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# --------------------------------
def get_prime_numbers(n):
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
ans = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1):
if is_prime(number):
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def prime_factorization(number):
# precondition
assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
ans = [] # this list will be returns of the function.
# potential prime number factors.
factor = 2
quotient = number
if number in {0, 1}:
ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(number):
while quotient != 1:
if is_prime(factor) and (quotient % factor == 0):
ans.append(factor)
quotient /= factor
else:
factor += 1
else:
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def greatest_prime_factor(number):
# precondition
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)
ans = 0
# prime factorization of 'number'
prime_factors = prime_factorization(number)
ans = max(prime_factors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------------------------------
def smallest_prime_factor(number):
# precondition
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and >= 0"
)
ans = 0
# prime factorization of 'number'
prime_factors = prime_factorization(number)
ans = min(prime_factors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------
def is_even(number):
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 == 0, bool), "compare must been from type bool"
return number % 2 == 0
# ------------------------
def is_odd(number):
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 != 0, bool), "compare must been from type bool"
return number % 2 != 0
# ------------------------
def goldbach(number):
# precondition
assert isinstance(number, int) and (number > 2) and is_even(number), (
"'number' must been an int, even and > 2"
)
ans = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
prime_numbers = get_prime_numbers(number)
len_pn = len(prime_numbers)
# run variable for while-loops.
i = 0
j = None
# exit variable. for break up the loops
loop = True
while i < len_pn and loop:
j = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
loop = False
ans.append(prime_numbers[i])
ans.append(prime_numbers[j])
j += 1
i += 1
# precondition
assert (
isinstance(ans, list)
and (len(ans) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0])
and is_prime(ans[1])
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
# ----------------------------------------------
def kg_v(number1, number2):
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 1)
and (number2 >= 1)
), "'number1' and 'number2' must been positive integer."
ans = 1 # actual answer that will be return.
# for kgV (x,1)
if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2'
prime_fac_1 = prime_factorization(number1)
prime_fac_2 = prime_factorization(number2)
elif number1 == 1 or number2 == 1:
prime_fac_1 = []
prime_fac_2 = []
ans = max(number1, number2)
count1 = 0
count2 = 0
done = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_1:
if n not in done:
if n in prime_fac_2:
count1 = prime_fac_1.count(n)
count2 = prime_fac_2.count(n)
for _ in range(max(count1, count2)):
ans *= n
else:
count1 = prime_fac_1.count(n)
for _ in range(count1):
ans *= n
done.append(n)
# iterates through primeFac2
for n in prime_fac_2:
if n not in done:
count2 = prime_fac_2.count(n)
for _ in range(count2):
ans *= n
done.append(n)
# precondition
assert isinstance(ans, int) and (ans >= 0), (
"'ans' must been from type int and positive"
)
return ans
# ----------------------------------
def get_prime(n):
# precondition
assert isinstance(n, int) and (n >= 0), "'number' must been a positive int"
index = 0
ans = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(ans):
ans += 1
# precondition
assert isinstance(ans, int) and is_prime(ans), (
"'ans' must been a prime number and from type int"
)
return ans
# ---------------------------------------------------
def get_primes_between(p_number_1, p_number_2):
# precondition
assert (
is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
number = p_number_1 + 1 # jump to the next number
ans = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(number):
number += 1
while number < p_number_2:
ans.append(number)
number += 1
# fetch the next prime number.
while not is_prime(number):
number += 1
# precondition
assert (
isinstance(ans, list)
and ans[0] != p_number_1
and ans[len(ans) - 1] != p_number_2
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
# ----------------------------------------------------
def get_divisors(n):
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
ans = [] # will be returned.
for divisor in range(1, n + 1):
if n % divisor == 0:
ans.append(divisor)
# precondition
assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)"
return ans
# ----------------------------------------------------
def is_perfect_number(number):
# precondition
assert isinstance(number, int) and (number > 1), (
"'number' must been an int and >= 1"
)
divisors = get_divisors(number)
# precondition
assert (
isinstance(divisors, list)
and (divisors[0] == 1)
and (divisors[len(divisors) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1]) == number
# ------------------------------------------------------------
def simplify_fraction(numerator, denominator):
# precondition
assert (
isinstance(numerator, int)
and isinstance(denominator, int)
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator))
# precondition
assert (
isinstance(gcd_of_fraction, int)
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd_by_iterative(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
# -----------------------------------------------------------------
def factorial(n):
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0"
ans = 1 # this will be return.
for factor in range(1, n + 1):
ans *= factor
return ans
# -------------------------------------------------------------------
def fib(n: int) -> int:
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for _ in range(n - 1):
tmp = ans
ans += fib1
fib1 = tmp
return ans
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,3 +1,41 @@+"""
+Created on Thu Oct 5 16:44:23 2017
+
+@author: Christian Bender
+
+This Python library contains some useful functions to deal with
+prime numbers and whole numbers.
+
+Overview:
+
+is_prime(number)
+sieve_er(N)
+get_prime_numbers(N)
+prime_factorization(number)
+greatest_prime_factor(number)
+smallest_prime_factor(number)
+get_prime(n)
+get_primes_between(pNumber1, pNumber2)
+
+----
+
+is_even(number)
+is_odd(number)
+kg_v(number1, number2) // least common multiple
+get_divisors(number) // all divisors of 'number' inclusive 1, number
+is_perfect_number(number)
+
+NEW-FUNCTIONS
+
+simplify_fraction(numerator, denominator)
+factorial (n) // n!
+fib (n) // calculate the n-th fibonacci term.
+
+-----
+
+goldbach(number) // Goldbach's assumption
+
+"""
from math import sqrt
@@ -5,6 +43,27 @@
def is_prime(number: int) -> bool:
+ """
+ input: positive integer 'number'
+ returns true if 'number' is prime otherwise false.
+
+ >>> is_prime(3)
+ True
+ >>> is_prime(10)
+ False
+ >>> is_prime(97)
+ True
+ >>> is_prime(9991)
+ False
+ >>> is_prime(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and positive
+ >>> is_prime("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and positive
+ """
# precondition
assert isinstance(number, int) and (number >= 0), (
@@ -34,6 +93,24 @@
def sieve_er(n):
+ """
+ input: positive integer 'N' > 2
+ returns a list of prime numbers from 2 up to N.
+
+ This function implements the algorithm called
+ sieve of erathostenes.
+
+ >>> sieve_er(8)
+ [2, 3, 5, 7]
+ >>> sieve_er(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'N' must been an int and > 2
+ >>> sieve_er("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'N' must been an int and > 2
+ """
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
@@ -62,6 +139,22 @@
def get_prime_numbers(n):
+ """
+ input: positive integer 'N' > 2
+ returns a list of prime numbers from 2 up to N (inclusive)
+ This function is more efficient as function 'sieveEr(...)'
+
+ >>> get_prime_numbers(8)
+ [2, 3, 5, 7]
+ >>> get_prime_numbers(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'N' must been an int and > 2
+ >>> get_prime_numbers("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'N' must been an int and > 2
+ """
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
@@ -84,6 +177,25 @@
def prime_factorization(number):
+ """
+ input: positive integer 'number'
+ returns a list of the prime number factors of 'number'
+
+ >>> prime_factorization(0)
+ [0]
+ >>> prime_factorization(8)
+ [2, 2, 2]
+ >>> prime_factorization(287)
+ [7, 41]
+ >>> prime_factorization(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ >>> prime_factorization("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ """
# precondition
assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
@@ -121,6 +233,25 @@
def greatest_prime_factor(number):
+ """
+ input: positive integer 'number' >= 0
+ returns the greatest prime number factor of 'number'
+
+ >>> greatest_prime_factor(0)
+ 0
+ >>> greatest_prime_factor(8)
+ 2
+ >>> greatest_prime_factor(287)
+ 41
+ >>> greatest_prime_factor(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ >>> greatest_prime_factor("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ """
# precondition
assert isinstance(number, int) and (number >= 0), (
@@ -144,6 +275,25 @@
def smallest_prime_factor(number):
+ """
+ input: integer 'number' >= 0
+ returns the smallest prime number factor of 'number'
+
+ >>> smallest_prime_factor(0)
+ 0
+ >>> smallest_prime_factor(8)
+ 2
+ >>> smallest_prime_factor(287)
+ 7
+ >>> smallest_prime_factor(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ >>> smallest_prime_factor("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 0
+ """
# precondition
assert isinstance(number, int) and (number >= 0), (
@@ -167,6 +317,23 @@
def is_even(number):
+ """
+ input: integer 'number'
+ returns true if 'number' is even, otherwise false.
+
+ >>> is_even(0)
+ True
+ >>> is_even(8)
+ True
+ >>> is_even(287)
+ False
+ >>> is_even(-1)
+ False
+ >>> is_even("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int
+ """
# precondition
assert isinstance(number, int), "'number' must been an int"
@@ -179,6 +346,23 @@
def is_odd(number):
+ """
+ input: integer 'number'
+ returns true if 'number' is odd, otherwise false.
+
+ >>> is_odd(0)
+ False
+ >>> is_odd(8)
+ False
+ >>> is_odd(287)
+ True
+ >>> is_odd(-1)
+ True
+ >>> is_odd("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int
+ """
# precondition
assert isinstance(number, int), "'number' must been an int"
@@ -191,6 +375,28 @@
def goldbach(number):
+ """
+ Goldbach's assumption
+ input: a even positive integer 'number' > 2
+ returns a list of two prime numbers whose sum is equal to 'number'
+
+ >>> goldbach(8)
+ [3, 5]
+ >>> goldbach(824)
+ [3, 821]
+ >>> goldbach(0)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int, even and > 2
+ >>> goldbach(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int, even and > 2
+ >>> goldbach("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int, even and > 2
+ """
# precondition
assert isinstance(number, int) and (number > 2) and is_even(number), (
@@ -239,6 +445,30 @@
def kg_v(number1, number2):
+ """
+ Least common multiple
+ input: two positive integer 'number1' and 'number2'
+ returns the least common multiple of 'number1' and 'number2'
+
+ >>> kg_v(8,10)
+ 40
+ >>> kg_v(824,67)
+ 55208
+ >>> kg_v(1, 10)
+ 10
+ >>> kg_v(0)
+ Traceback (most recent call last):
+ ...
+ TypeError: kg_v() missing 1 required positional argument: 'number2'
+ >>> kg_v(10,-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number1' and 'number2' must been positive integer.
+ >>> kg_v("test","test2")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number1' and 'number2' must been positive integer.
+ """
# precondition
assert (
@@ -306,6 +536,26 @@
def get_prime(n):
+ """
+ Gets the n-th prime number.
+ input: positive integer 'n' >= 0
+ returns the n-th prime number, beginning at index 0
+
+ >>> get_prime(0)
+ 2
+ >>> get_prime(8)
+ 23
+ >>> get_prime(824)
+ 6337
+ >>> get_prime(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been a positive int
+ >>> get_prime("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been a positive int
+ """
# precondition
assert isinstance(n, int) and (n >= 0), "'number' must been a positive int"
@@ -335,6 +585,31 @@
def get_primes_between(p_number_1, p_number_2):
+ """
+ input: prime numbers 'pNumber1' and 'pNumber2'
+ pNumber1 < pNumber2
+ returns a list of all prime numbers between 'pNumber1' (exclusive)
+ and 'pNumber2' (exclusive)
+
+ >>> get_primes_between(3, 67)
+ [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]
+ >>> get_primes_between(0)
+ Traceback (most recent call last):
+ ...
+ TypeError: get_primes_between() missing 1 required positional argument: 'p_number_2'
+ >>> get_primes_between(0, 1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: The arguments must been prime numbers and 'pNumber1' < 'pNumber2'
+ >>> get_primes_between(-1, 3)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and positive
+ >>> get_primes_between("test","test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and positive
+ """
# precondition
assert (
@@ -374,6 +649,23 @@
def get_divisors(n):
+ """
+ input: positive integer 'n' >= 1
+ returns all divisors of n (inclusive 1 and 'n')
+
+ >>> get_divisors(8)
+ [1, 2, 4, 8]
+ >>> get_divisors(824)
+ [1, 2, 4, 8, 103, 206, 412, 824]
+ >>> get_divisors(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been int and >= 1
+ >>> get_divisors("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been int and >= 1
+ """
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
@@ -394,6 +686,23 @@
def is_perfect_number(number):
+ """
+ input: positive integer 'number' > 1
+ returns true if 'number' is a perfect number otherwise false.
+
+ >>> is_perfect_number(28)
+ True
+ >>> is_perfect_number(824)
+ False
+ >>> is_perfect_number(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 1
+ >>> is_perfect_number("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'number' must been an int and >= 1
+ """
# precondition
assert isinstance(number, int) and (number > 1), (
@@ -417,6 +726,20 @@
def simplify_fraction(numerator, denominator):
+ """
+ input: two integer 'numerator' and 'denominator'
+ assumes: 'denominator' != 0
+ returns: a tuple with simplify numerator and denominator.
+
+ >>> simplify_fraction(10, 20)
+ (1, 2)
+ >>> simplify_fraction(10, -1)
+ (10, -1)
+ >>> simplify_fraction("test","test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: The arguments must been from type int and 'denominator' != 0
+ """
# precondition
assert (
@@ -442,6 +765,23 @@
def factorial(n):
+ """
+ input: positive integer 'n'
+ returns the factorial of 'n' (n!)
+
+ >>> factorial(0)
+ 1
+ >>> factorial(20)
+ 2432902008176640000
+ >>> factorial(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been a int and >= 0
+ >>> factorial("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been a int and >= 0
+ """
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0"
@@ -458,6 +798,27 @@
def fib(n: int) -> int:
+ """
+ input: positive integer 'n'
+ returns the n-th fibonacci term , indexing by 0
+
+ >>> fib(0)
+ 1
+ >>> fib(5)
+ 8
+ >>> fib(20)
+ 10946
+ >>> fib(99)
+ 354224848179261915075
+ >>> fib(-1)
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been an int and >= 0
+ >>> fib("test")
+ Traceback (most recent call last):
+ ...
+ AssertionError: 'n' must been an int and >= 0
+ """
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
@@ -477,4 +838,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/primelib.py |
Help me write clear docstrings |
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(a_limit: int = 1000, b_limit: int = 1000) -> int:
longest = [0, 0, 0] # length, a, b
for a in range((a_limit * -1) + 1, a_limit):
for b in range(2, b_limit):
if is_prime(b):
count = 0
n = 0
while is_prime((n**2) + (a * n) + b):
count += 1
n += 1
if count > longest[0]:
longest = [count, a, b]
ans = longest[1] * longest[2]
return ans
if __name__ == "__main__":
print(solution(1000, 1000)) | --- +++ @@ -1,8 +1,49 @@+"""
+Project Euler Problem 27
+https://projecteuler.net/problem=27
+
+Problem Statement:
+
+Euler discovered the remarkable quadratic formula:
+n2 + n + 41
+It turns out that the formula will produce 40 primes for the consecutive values
+n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible
+by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41.
+The incredible formula n2 - 79n + 1601 was discovered, which produces 80 primes
+for the consecutive values n = 0 to 79. The product of the coefficients, -79 and
+1601, is -126479.
+Considering quadratics of the form:
+n² + an + b, where |a| < 1000 and |b| < 1000
+where |n| is the modulus/absolute value of ne.g. |11| = 11 and |-4| = 4
+Find the product of the coefficients, a and b, for the quadratic expression that
+produces the maximum number of primes for consecutive values of n, starting with
+n = 0.
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+ A number is prime if it has exactly two factors: 1 and itself.
+ Returns boolean representing primality of given number num (i.e., if the
+ result is true, then the number is indeed prime else it is not).
+
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(2999)
+ True
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(-10)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,6 +60,18 @@
def solution(a_limit: int = 1000, b_limit: int = 1000) -> int:
+ """
+ >>> solution(1000, 1000)
+ -59231
+ >>> solution(200, 1000)
+ -59231
+ >>> solution(200, 200)
+ -4925
+ >>> solution(-1000, 1000)
+ 0
+ >>> solution(-1000, -1000)
+ 0
+ """
longest = [0, 0, 0] # length, a, b
for a in range((a_limit * -1) + 1, a_limit):
for b in range(2, b_limit):
@@ -35,4 +88,4 @@
if __name__ == "__main__":
- print(solution(1000, 1000))+ print(solution(1000, 1000))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_027/sol1.py |
Generate docstrings for each module |
def solution(numerator: int = 1, digit: int = 1000) -> int:
the_digit = 1
longest_list_length = 0
for divide_by_number in range(numerator, digit + 1):
has_been_divided: list[int] = []
now_divide = numerator
for _ in range(1, digit + 1):
if now_divide in has_been_divided:
if longest_list_length < len(has_been_divided):
longest_list_length = len(has_been_divided)
the_digit = divide_by_number
else:
has_been_divided.append(now_divide)
now_divide = now_divide * 10 % divide_by_number
return the_digit
# Tests
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,40 @@+"""
+Euler Problem 26
+https://projecteuler.net/problem=26
+
+Problem Statement:
+
+A unit fraction contains 1 in the numerator. The decimal representation of the
+unit fractions with denominators 2 to 10 are given:
+
+1/2 = 0.5
+1/3 = 0.(3)
+1/4 = 0.25
+1/5 = 0.2
+1/6 = 0.1(6)
+1/7 = 0.(142857)
+1/8 = 0.125
+1/9 = 0.(1)
+1/10 = 0.1
+Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be
+seen that 1/7 has a 6-digit recurring cycle.
+
+Find the value of d < 1000 for which 1/d contains the longest recurring cycle
+in its decimal fraction part.
+"""
def solution(numerator: int = 1, digit: int = 1000) -> int:
+ """
+ Considering any range can be provided,
+ because as per the problem, the digit d < 1000
+ >>> solution(1, 10)
+ 7
+ >>> solution(10, 100)
+ 97
+ >>> solution(10, 1000)
+ 983
+ """
the_digit = 1
longest_list_length = 0
@@ -23,4 +57,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_026/sol1.py |
Generate descriptive docstrings automatically | from collections.abc import Sequence
def evaluate_poly(poly: Sequence[float], x: float) -> float:
return sum(c * (x**i) for i, c in enumerate(poly))
def horner(poly: Sequence[float], x: float) -> float:
result = 0.0
for coeff in reversed(poly):
result = result * x + coeff
return result
if __name__ == "__main__":
"""
Example:
>>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2
>>> x = -13.0
>>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9
>>> evaluate_poly(poly, x)
180339.9
"""
poly = (0.0, 0.0, 5.0, 9.3, 7.0)
x = 10.0
print(evaluate_poly(poly, x))
print(horner(poly, x)) | --- +++ @@ -2,10 +2,37 @@
def evaluate_poly(poly: Sequence[float], x: float) -> float:
+ """Evaluate a polynomial f(x) at specified point x and return the value.
+
+ Arguments:
+ poly -- the coefficients of a polynomial as an iterable in order of
+ ascending degree
+ x -- the point at which to evaluate the polynomial
+
+ >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
+ 79800.0
+ """
return sum(c * (x**i) for i, c in enumerate(poly))
def horner(poly: Sequence[float], x: float) -> float:
+ """Evaluate a polynomial at specified point using Horner's method.
+
+ In terms of computational complexity, Horner's method is an efficient method
+ of evaluating a polynomial. It avoids the use of expensive exponentiation,
+ and instead uses only multiplication and addition to evaluate the polynomial
+ in O(n), where n is the degree of the polynomial.
+
+ https://en.wikipedia.org/wiki/Horner's_method
+
+ Arguments:
+ poly -- the coefficients of a polynomial as an iterable in order of
+ ascending degree
+ x -- the point at which to evaluate the polynomial
+
+ >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
+ 79800.0
+ """
result = 0.0
for coeff in reversed(poly):
result = result * x + coeff
@@ -24,4 +51,4 @@ poly = (0.0, 0.0, 5.0, 9.3, 7.0)
x = 10.0
print(evaluate_poly(poly, x))
- print(horner(poly, x))+ print(horner(poly, x))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/polynomial_evaluation.py |
Add concise docstrings to each method |
DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)}
def digits_fifth_powers_sum(number: int) -> int:
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number))
def solution() -> int:
return sum(
number
for number in range(1000, 1000000)
if number == digits_fifth_powers_sum(number)
)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,34 @@+"""Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30
+
+Surprisingly there are only three numbers that can be written as the sum of fourth
+powers of their digits:
+
+1634 = 1^4 + 6^4 + 3^4 + 4^4
+8208 = 8^4 + 2^4 + 0^4 + 8^4
+9474 = 9^4 + 4^4 + 7^4 + 4^4
+As 1 = 1^4 is not a sum it is not included.
+
+The sum of these numbers is 1634 + 8208 + 9474 = 19316.
+
+Find the sum of all the numbers that can be written as the sum of fifth powers of their
+digits.
+
+9^5 = 59049
+59049 * 7 = 413343 (which is only 6 digit number)
+So, numbers greater than 999999 are rejected
+and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit)
+So, number > 999
+and hence a number between 1000 and 1000000
+"""
DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)}
def digits_fifth_powers_sum(number: int) -> int:
+ """
+ >>> digits_fifth_powers_sum(1234)
+ 1300
+ """
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number))
@@ -15,4 +41,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_030/sol1.py |
Add concise docstrings to each method |
import itertools
def is_combination_valid(combination):
return (
int("".join(combination[0:2])) * int("".join(combination[2:5]))
== int("".join(combination[5:9]))
) or (
int("".join(combination[0])) * int("".join(combination[1:5]))
== int("".join(combination[5:9]))
)
def solution():
return sum(
{
int("".join(pandigital[5:9]))
for pandigital in itertools.permutations("123456789")
if is_combination_valid(pandigital)
}
)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,33 @@+"""
+We shall say that an n-digit number is pandigital if it makes use of all the
+digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through
+5 pandigital.
+
+The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing
+multiplicand, multiplier, and product is 1 through 9 pandigital.
+
+Find the sum of all products whose multiplicand/multiplier/product identity can
+be written as a 1 through 9 pandigital.
+
+HINT: Some products can be obtained in more than one way so be sure to only
+include it once in your sum.
+"""
import itertools
def is_combination_valid(combination):
+ """
+ Checks if a combination (a tuple of 9 digits)
+ is a valid product equation.
+
+ >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4'))
+ True
+
+ >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
+ False
+
+ """
return (
int("".join(combination[0:2])) * int("".join(combination[2:5]))
== int("".join(combination[5:9]))
@@ -13,6 +38,13 @@
def solution():
+ """
+ Finds the sum of all products whose multiplicand/multiplier/product identity
+ can be written as a 1 through 9 pandigital
+
+ >>> solution()
+ 45228
+ """
return sum(
{
@@ -24,4 +56,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_032/sol32.py |
Generate consistent docstrings |
def one_pence() -> int:
return 1
def two_pence(x: int) -> int:
return 0 if x < 0 else two_pence(x - 2) + one_pence()
def five_pence(x: int) -> int:
return 0 if x < 0 else five_pence(x - 5) + two_pence(x)
def ten_pence(x: int) -> int:
return 0 if x < 0 else ten_pence(x - 10) + five_pence(x)
def twenty_pence(x: int) -> int:
return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x)
def fifty_pence(x: int) -> int:
return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x)
def one_pound(x: int) -> int:
return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x)
def two_pound(x: int) -> int:
return 0 if x < 0 else two_pound(x - 200) + one_pound(x)
def solution(n: int = 200) -> int:
return two_pound(n)
if __name__ == "__main__":
print(solution(int(input().strip()))) | --- +++ @@ -1,3 +1,16 @@+"""
+Coin sums
+Problem 31: https://projecteuler.net/problem=31
+
+In England the currency is made up of pound, f, and pence, p, and there are
+eight coins in general circulation:
+
+1p, 2p, 5p, 10p, 20p, 50p, f1 (100p) and f2 (200p).
+It is possible to make f2 in the following way:
+
+1xf1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p
+How many different ways can f2 be made using any number of coins?
+"""
def one_pence() -> int:
@@ -33,8 +46,20 @@
def solution(n: int = 200) -> int:
+ """Returns the number of different ways can n pence be made using any number of
+ coins?
+
+ >>> solution(500)
+ 6295434
+ >>> solution(200)
+ 73682
+ >>> solution(50)
+ 451
+ >>> solution(10)
+ 11
+ """
return two_pound(n)
if __name__ == "__main__":
- print(solution(int(input().strip())))+ print(solution(int(input().strip())))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_031/sol1.py |
Document this code for team use |
def solution(pence: int = 200) -> int:
coins = [1, 2, 5, 10, 20, 50, 100, 200]
number_of_ways = [0] * (pence + 1)
number_of_ways[0] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(coin, pence + 1, 1):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73682 | --- +++ @@ -1,6 +1,50 @@+"""
+Problem 31: https://projecteuler.net/problem=31
+
+Coin sums
+
+In England the currency is made up of pound, f, and pence, p, and there are
+eight coins in general circulation:
+
+1p, 2p, 5p, 10p, 20p, 50p, f1 (100p) and f2 (200p).
+It is possible to make f2 in the following way:
+
+1xf1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p
+How many different ways can f2 be made using any number of coins?
+
+Hint:
+ > There are 100 pence in a pound (f1 = 100p)
+ > There are coins(in pence) are available: 1, 2, 5, 10, 20, 50, 100 and 200.
+ > how many different ways you can combine these values to create 200 pence.
+
+Example:
+ to make 6p there are 5 ways
+ 1,1,1,1,1,1
+ 1,1,1,1,2
+ 1,1,2,2
+ 2,2,2
+ 1,5
+ to make 5p there are 4 ways
+ 1,1,1,1,1
+ 1,1,1,2
+ 1,2,2
+ 5
+"""
def solution(pence: int = 200) -> int:
+ """Returns the number of different ways to make X pence using any number of coins.
+ The solution is based on dynamic programming paradigm in a bottom-up fashion.
+
+ >>> solution(500)
+ 6295434
+ >>> solution(200)
+ 73682
+ >>> solution(50)
+ 451
+ >>> solution(10)
+ 11
+ """
coins = [1, 2, 5, 10, 20, 50, 100, 200]
number_of_ways = [0] * (pence + 1)
number_of_ways[0] = 1 # base case: 1 way to make 0 pence
@@ -12,4 +56,4 @@
if __name__ == "__main__":
- assert solution(200) == 73682+ assert solution(200) == 73682
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_031/sol2.py |
Generate consistent documentation across files |
from math import factorial
DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)}
def sum_of_digit_factorial(n: int) -> int:
return sum(DIGIT_FACTORIAL[d] for d in str(n))
def solution() -> int:
limit = 7 * factorial(9) + 1
return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,17 +1,38 @@-
-from math import factorial
-
-DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)}
-
-
-def sum_of_digit_factorial(n: int) -> int:
- return sum(DIGIT_FACTORIAL[d] for d in str(n))
-
-
-def solution() -> int:
- limit = 7 * factorial(9) + 1
- return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Problem 34: https://projecteuler.net/problem=34
+
+145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
+Find the sum of all numbers which are equal to the sum of the factorial of their digits.
+Note: As 1! = 1 and 2! = 2 are not sums they are not included.
+"""
+
+from math import factorial
+
+DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)}
+
+
+def sum_of_digit_factorial(n: int) -> int:
+ """
+ Returns the sum of the factorial of digits in n
+ >>> sum_of_digit_factorial(15)
+ 121
+ >>> sum_of_digit_factorial(0)
+ 1
+ """
+ return sum(DIGIT_FACTORIAL[d] for d in str(n))
+
+
+def solution() -> int:
+ """
+ Returns the sum of all numbers whose
+ sum of the factorials of all digits
+ add up to the number itself.
+ >>> solution()
+ 40730
+ """
+ limit = 7 * factorial(9) + 1
+ return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_034/sol1.py |
Generate docstrings for script automation |
from __future__ import annotations
sieve = [True] * 1000001
i = 2
while i * i <= 1000000:
if sieve[i]:
for j in range(i * i, 1000001, i):
sieve[j] = False
i += 1
def is_prime(n: int) -> bool:
return sieve[n]
def contains_an_even_digit(n: int) -> bool:
return any(digit in "02468" for digit in str(n))
def find_circular_primes(limit: int = 1000000) -> list[int]:
result = [2] # result already includes the number 2.
for num in range(3, limit + 1, 2):
if is_prime(num) and not contains_an_even_digit(num):
str_num = str(num)
list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))]
if all(is_prime(i) for i in list_nums):
result.append(num)
return result
def solution() -> int:
return len(find_circular_primes())
if __name__ == "__main__":
print(f"{len(find_circular_primes()) = }") | --- +++ @@ -1,37 +1,83 @@-
-from __future__ import annotations
-
-sieve = [True] * 1000001
-i = 2
-while i * i <= 1000000:
- if sieve[i]:
- for j in range(i * i, 1000001, i):
- sieve[j] = False
- i += 1
-
-
-def is_prime(n: int) -> bool:
- return sieve[n]
-
-
-def contains_an_even_digit(n: int) -> bool:
- return any(digit in "02468" for digit in str(n))
-
-
-def find_circular_primes(limit: int = 1000000) -> list[int]:
- result = [2] # result already includes the number 2.
- for num in range(3, limit + 1, 2):
- if is_prime(num) and not contains_an_even_digit(num):
- str_num = str(num)
- list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))]
- if all(is_prime(i) for i in list_nums):
- result.append(num)
- return result
-
-
-def solution() -> int:
- return len(find_circular_primes())
-
-
-if __name__ == "__main__":
- print(f"{len(find_circular_primes()) = }")+"""
+Project Euler Problem 35
+https://projecteuler.net/problem=35
+
+Problem Statement:
+
+The number 197 is called a circular prime because all rotations of the digits:
+197, 971, and 719, are themselves prime.
+There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73,
+79, and 97.
+How many circular primes are there below one million?
+
+To solve this problem in an efficient manner, we will first mark all the primes
+below 1 million using the Sieve of Eratosthenes. Then, out of all these primes,
+we will rule out the numbers which contain an even digit. After this we will
+generate each circular combination of the number and check if all are prime.
+"""
+
+from __future__ import annotations
+
+sieve = [True] * 1000001
+i = 2
+while i * i <= 1000000:
+ if sieve[i]:
+ for j in range(i * i, 1000001, i):
+ sieve[j] = False
+ i += 1
+
+
+def is_prime(n: int) -> bool:
+ """
+ For 2 <= n <= 1000000, return True if n is prime.
+ >>> is_prime(87)
+ False
+ >>> is_prime(23)
+ True
+ >>> is_prime(25363)
+ False
+ """
+ return sieve[n]
+
+
+def contains_an_even_digit(n: int) -> bool:
+ """
+ Return True if n contains an even digit.
+ >>> contains_an_even_digit(0)
+ True
+ >>> contains_an_even_digit(975317933)
+ False
+ >>> contains_an_even_digit(-245679)
+ True
+ """
+ return any(digit in "02468" for digit in str(n))
+
+
+def find_circular_primes(limit: int = 1000000) -> list[int]:
+ """
+ Return circular primes below limit.
+ >>> len(find_circular_primes(100))
+ 13
+ >>> len(find_circular_primes(1000000))
+ 55
+ """
+ result = [2] # result already includes the number 2.
+ for num in range(3, limit + 1, 2):
+ if is_prime(num) and not contains_an_even_digit(num):
+ str_num = str(num)
+ list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))]
+ if all(is_prime(i) for i in list_nums):
+ result.append(num)
+ return result
+
+
+def solution() -> int:
+ """
+ >>> solution()
+ 55
+ """
+ return len(find_circular_primes())
+
+
+if __name__ == "__main__":
+ print(f"{len(find_circular_primes()) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_035/sol1.py |
Auto-generate documentation strings for this file |
from __future__ import annotations
from fractions import Fraction
def is_digit_cancelling(num: int, den: int) -> bool:
return (
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
)
def fraction_list(digit_len: int) -> list[str]:
solutions = []
den = 11
last_digit = int("1" + "0" * digit_len)
for num in range(den, last_digit):
while den <= 99:
if (
(num != den)
and (num % 10 == den // 10)
and (den % 10 != 0)
and is_digit_cancelling(num, den)
):
solutions.append(f"{num}/{den}")
den += 1
num += 1
den = 10
return solutions
def solution(n: int = 2) -> int:
result = 1.0
for fraction in fraction_list(n):
frac = Fraction(fraction)
result *= frac.denominator / frac.numerator
return int(result)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,19 @@+"""
+Problem 33: https://projecteuler.net/problem=33
+
+The fraction 49/98 is a curious fraction, as an inexperienced
+mathematician in attempting to simplify it may incorrectly believe
+that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
+
+We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
+
+There are exactly four non-trivial examples of this type of fraction,
+less than one in value, and containing two digits in the numerator
+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
@@ -11,6 +27,18 @@
def fraction_list(digit_len: int) -> list[str]:
+ """
+ >>> fraction_list(2)
+ ['16/64', '19/95', '26/65', '49/98']
+ >>> fraction_list(3)
+ ['16/64', '19/95', '26/65', '49/98']
+ >>> fraction_list(4)
+ ['16/64', '19/95', '26/65', '49/98']
+ >>> fraction_list(0)
+ []
+ >>> fraction_list(5)
+ ['16/64', '19/95', '26/65', '49/98']
+ """
solutions = []
den = 11
last_digit = int("1" + "0" * digit_len)
@@ -30,6 +58,9 @@
def solution(n: int = 2) -> int:
+ """
+ Return the solution to the problem
+ """
result = 1.0
for fraction in fraction_list(n):
frac = Fraction(fraction)
@@ -38,4 +69,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_033/sol1.py |
Add concise docstrings to each method |
from __future__ import annotations
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def list_truncated_nums(n: int) -> list[int]:
str_num = str(n)
list_nums = [n]
for i in range(1, len(str_num)):
list_nums.append(int(str_num[i:]))
list_nums.append(int(str_num[:-i]))
return list_nums
def validate(n: int) -> bool:
return not (
len(str(n)) > 3
and (not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])))
)
def compute_truncated_primes(count: int = 11) -> list[int]:
list_truncated_primes: list[int] = []
num = 13
while len(list_truncated_primes) != count:
if validate(num):
list_nums = list_truncated_nums(num)
if all(is_prime(i) for i in list_nums):
list_truncated_primes.append(num)
num += 2
return list_truncated_primes
def solution() -> int:
return sum(compute_truncated_primes(11))
if __name__ == "__main__":
print(f"{sum(compute_truncated_primes(11)) = }") | --- +++ @@ -1,56 +1,119 @@-
-from __future__ import annotations
-
-import math
-
-
-def is_prime(number: int) -> bool:
-
- if 1 < number < 4:
- # 2 and 3 are primes
- return True
- elif number < 2 or number % 2 == 0 or number % 3 == 0:
- # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
- return False
-
- # All primes number are in format of 6k +/- 1
- for i in range(5, int(math.sqrt(number) + 1), 6):
- if number % i == 0 or number % (i + 2) == 0:
- return False
- return True
-
-
-def list_truncated_nums(n: int) -> list[int]:
- str_num = str(n)
- list_nums = [n]
- for i in range(1, len(str_num)):
- list_nums.append(int(str_num[i:]))
- list_nums.append(int(str_num[:-i]))
- return list_nums
-
-
-def validate(n: int) -> bool:
- return not (
- len(str(n)) > 3
- and (not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])))
- )
-
-
-def compute_truncated_primes(count: int = 11) -> list[int]:
- list_truncated_primes: list[int] = []
- num = 13
- while len(list_truncated_primes) != count:
- if validate(num):
- list_nums = list_truncated_nums(num)
- if all(is_prime(i) for i in list_nums):
- list_truncated_primes.append(num)
- num += 2
- return list_truncated_primes
-
-
-def solution() -> int:
- return sum(compute_truncated_primes(11))
-
-
-if __name__ == "__main__":
- print(f"{sum(compute_truncated_primes(11)) = }")+"""
+Truncatable primes
+Problem 37: https://projecteuler.net/problem=37
+
+The number 3797 has an interesting property. Being prime itself, it is possible
+to continuously remove digits from left to right, and remain prime at each stage:
+3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
+
+Find the sum of the only eleven primes that are both truncatable from left to right
+and right to left.
+
+NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
+"""
+
+from __future__ import annotations
+
+import math
+
+
+def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(87)
+ False
+ >>> is_prime(563)
+ True
+ >>> is_prime(2999)
+ True
+ >>> is_prime(67483)
+ False
+ """
+
+ if 1 < number < 4:
+ # 2 and 3 are primes
+ return True
+ elif number < 2 or number % 2 == 0 or number % 3 == 0:
+ # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
+ return False
+
+ # All primes number are in format of 6k +/- 1
+ for i in range(5, int(math.sqrt(number) + 1), 6):
+ if number % i == 0 or number % (i + 2) == 0:
+ return False
+ return True
+
+
+def list_truncated_nums(n: int) -> list[int]:
+ """
+ Returns a list of all left and right truncated numbers of n
+ >>> list_truncated_nums(927628)
+ [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9]
+ >>> list_truncated_nums(467)
+ [467, 67, 46, 7, 4]
+ >>> list_truncated_nums(58)
+ [58, 8, 5]
+ """
+ str_num = str(n)
+ list_nums = [n]
+ for i in range(1, len(str_num)):
+ list_nums.append(int(str_num[i:]))
+ list_nums.append(int(str_num[:-i]))
+ return list_nums
+
+
+def validate(n: int) -> bool:
+ """
+ To optimize the approach, we will rule out the numbers above 1000,
+ whose first or last three digits are not prime
+ >>> validate(74679)
+ False
+ >>> validate(235693)
+ False
+ >>> validate(3797)
+ True
+ """
+ return not (
+ len(str(n)) > 3
+ and (not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])))
+ )
+
+
+def compute_truncated_primes(count: int = 11) -> list[int]:
+ """
+ Returns the list of truncated primes
+ >>> compute_truncated_primes(11)
+ [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397]
+ """
+ list_truncated_primes: list[int] = []
+ num = 13
+ while len(list_truncated_primes) != count:
+ if validate(num):
+ list_nums = list_truncated_nums(num)
+ if all(is_prime(i) for i in list_nums):
+ list_truncated_primes.append(num)
+ num += 2
+ return list_truncated_primes
+
+
+def solution() -> int:
+ """
+ Returns the sum of truncated primes
+ """
+ return sum(compute_truncated_primes(11))
+
+
+if __name__ == "__main__":
+ print(f"{sum(compute_truncated_primes(11)) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_037/sol1.py |
Add docstrings that explain inputs and outputs |
import mpmath # for roots of unity
import numpy as np
class FFT:
def __init__(self, poly_a=None, poly_b=None):
# Input as list
self.polyA = list(poly_a or [0])[:]
self.polyB = list(poly_b or [0])[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
self.len_A = len(self.polyA)
while self.polyB[-1] == 0:
self.polyB.pop()
self.len_B = len(self.polyB)
# Add 0 to make lengths equal a power of 2
self.c_max_length = int(
2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))
)
while len(self.polyA) < self.c_max_length:
self.polyA.append(0)
while len(self.polyB) < self.c_max_length:
self.polyB.append(0)
# A complex root used for the fourier transform
self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1))
# The product
self.product = self.__multiply()
# Discrete fourier transform of A and B
def __dft(self, which):
dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(dft) <= 1:
return dft[0]
next_ncol = self.c_max_length // 2
while next_ncol > 0:
new_dft = [[] for i in range(next_ncol)]
root = self.root**next_ncol
# First half of next step
current_root = 1
for j in range(self.c_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
current_root *= root
# Second half of next step
current_root = 1
for j in range(self.c_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
current_root *= root
# Update
dft = new_dft
next_ncol = next_ncol // 2
return dft[0]
# multiply the DFTs of A and B and find A*B
def __multiply(self):
dft_a = self.__dft("A")
dft_b = self.__dft("B")
inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0]) <= 1:
return inverce_c[0]
# Inverse DFT
next_ncol = 2
while next_ncol <= self.c_max_length:
new_inverse_c = [[] for i in range(next_ncol)]
root = self.root ** (next_ncol // 2)
current_root = 1
# First half of next step
for j in range(self.c_max_length // next_ncol):
for i in range(next_ncol // 2):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2
)
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root)
)
current_root *= root
# Update
inverce_c = new_inverse_c
next_ncol *= 2
# Unpack
inverce_c = [
complex(round(x[0].real, 8), round(x[0].imag, 8)) for x in inverce_c
]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
# Overwrite __str__ for print(); Shows A, B and A*B
def __str__(self):
a = "A = " + " + ".join(
f"{coef}*x^{i}" for i, coef in enumerate(self.polyA[: self.len_A])
)
b = "B = " + " + ".join(
f"{coef}*x^{i}" for i, coef in enumerate(self.polyB[: self.len_B])
)
c = "A*B = " + " + ".join(
f"{coef}*x^{i}" for i, coef in enumerate(self.product)
)
return f"{a}\n{b}\n{c}"
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,134 +1,178 @@-
-import mpmath # for roots of unity
-import numpy as np
-
-
-class FFT:
-
- def __init__(self, poly_a=None, poly_b=None):
- # Input as list
- self.polyA = list(poly_a or [0])[:]
- self.polyB = list(poly_b or [0])[:]
-
- # Remove leading zero coefficients
- while self.polyA[-1] == 0:
- self.polyA.pop()
- self.len_A = len(self.polyA)
-
- while self.polyB[-1] == 0:
- self.polyB.pop()
- self.len_B = len(self.polyB)
-
- # Add 0 to make lengths equal a power of 2
- self.c_max_length = int(
- 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))
- )
-
- while len(self.polyA) < self.c_max_length:
- self.polyA.append(0)
- while len(self.polyB) < self.c_max_length:
- self.polyB.append(0)
- # A complex root used for the fourier transform
- self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1))
-
- # The product
- self.product = self.__multiply()
-
- # Discrete fourier transform of A and B
- def __dft(self, which):
- dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
- # Corner case
- if len(dft) <= 1:
- return dft[0]
- next_ncol = self.c_max_length // 2
- while next_ncol > 0:
- new_dft = [[] for i in range(next_ncol)]
- root = self.root**next_ncol
-
- # First half of next step
- current_root = 1
- for j in range(self.c_max_length // (next_ncol * 2)):
- for i in range(next_ncol):
- new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
- current_root *= root
- # Second half of next step
- current_root = 1
- for j in range(self.c_max_length // (next_ncol * 2)):
- for i in range(next_ncol):
- new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
- current_root *= root
- # Update
- dft = new_dft
- next_ncol = next_ncol // 2
- return dft[0]
-
- # multiply the DFTs of A and B and find A*B
- def __multiply(self):
- dft_a = self.__dft("A")
- dft_b = self.__dft("B")
- inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
- del dft_a
- del dft_b
-
- # Corner Case
- if len(inverce_c[0]) <= 1:
- return inverce_c[0]
- # Inverse DFT
- next_ncol = 2
- while next_ncol <= self.c_max_length:
- new_inverse_c = [[] for i in range(next_ncol)]
- root = self.root ** (next_ncol // 2)
- current_root = 1
- # First half of next step
- for j in range(self.c_max_length // next_ncol):
- for i in range(next_ncol // 2):
- # Even positions
- new_inverse_c[i].append(
- (
- inverce_c[i][j]
- + inverce_c[i][j + self.c_max_length // next_ncol]
- )
- / 2
- )
- # Odd positions
- new_inverse_c[i + next_ncol // 2].append(
- (
- inverce_c[i][j]
- - inverce_c[i][j + self.c_max_length // next_ncol]
- )
- / (2 * current_root)
- )
- current_root *= root
- # Update
- inverce_c = new_inverse_c
- next_ncol *= 2
- # Unpack
- inverce_c = [
- complex(round(x[0].real, 8), round(x[0].imag, 8)) for x in inverce_c
- ]
-
- # Remove leading 0's
- while inverce_c[-1] == 0:
- inverce_c.pop()
- return inverce_c
-
- # Overwrite __str__ for print(); Shows A, B and A*B
- def __str__(self):
- a = "A = " + " + ".join(
- f"{coef}*x^{i}" for i, coef in enumerate(self.polyA[: self.len_A])
- )
- b = "B = " + " + ".join(
- f"{coef}*x^{i}" for i, coef in enumerate(self.polyB[: self.len_B])
- )
- c = "A*B = " + " + ".join(
- f"{coef}*x^{i}" for i, coef in enumerate(self.product)
- )
-
- return f"{a}\n{b}\n{c}"
-
-
-# Unit tests
-if __name__ == "__main__":
- import doctest
-
- doctest.testmod()+"""
+Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
+"""
+
+import mpmath # for roots of unity
+import numpy as np
+
+
+class FFT:
+ """
+ Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
+
+ Reference:
+ https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case
+
+ For polynomials of degree m and n the algorithms has complexity
+ O(n*logn + m*logm)
+
+ The main part of the algorithm is split in two parts:
+ 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a
+ bottom-up dynamic approach -
+ 2) __multiply: Once we obtain the DFT of A*B, we can similarly
+ invert it to obtain A*B
+
+ The class FFT takes two polynomials A and B with complex coefficients as arguments;
+ The two polynomials should be represented as a sequence of coefficients starting
+ from the free term. Thus, for instance x + 2*x^3 could be represented as
+ [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the
+ polynomials have the same length which is a power of 2 at least the length of
+ their product.
+
+ Example:
+
+ Create two polynomials as sequences
+ >>> A = [0, 1, 0, 2] # x+2x^3
+ >>> B = (2, 3, 4, 0) # 2+3x+4x^2
+
+ Create an FFT object with them
+ >>> x = FFT(A, B)
+
+ Print product
+ >>> x.product # 2x + 3x^2 + 8x^3 + 6x^4 + 8x^5
+ [(-0-0j), (2+0j), (3-0j), (8-0j), (6+0j), (8+0j)]
+
+ __str__ test
+ >>> print(x)
+ A = 0*x^0 + 1*x^1 + 0*x^2 + 2*x^3
+ B = 2*x^0 + 3*x^1 + 4*x^2
+ A*B = (-0-0j)*x^0 + (2+0j)*x^1 + (3-0j)*x^2 + (8-0j)*x^3 + (6+0j)*x^4 + (8+0j)*x^5
+ """
+
+ def __init__(self, poly_a=None, poly_b=None):
+ # Input as list
+ self.polyA = list(poly_a or [0])[:]
+ self.polyB = list(poly_b or [0])[:]
+
+ # Remove leading zero coefficients
+ while self.polyA[-1] == 0:
+ self.polyA.pop()
+ self.len_A = len(self.polyA)
+
+ while self.polyB[-1] == 0:
+ self.polyB.pop()
+ self.len_B = len(self.polyB)
+
+ # Add 0 to make lengths equal a power of 2
+ self.c_max_length = int(
+ 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))
+ )
+
+ while len(self.polyA) < self.c_max_length:
+ self.polyA.append(0)
+ while len(self.polyB) < self.c_max_length:
+ self.polyB.append(0)
+ # A complex root used for the fourier transform
+ self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1))
+
+ # The product
+ self.product = self.__multiply()
+
+ # Discrete fourier transform of A and B
+ def __dft(self, which):
+ dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
+ # Corner case
+ if len(dft) <= 1:
+ return dft[0]
+ next_ncol = self.c_max_length // 2
+ while next_ncol > 0:
+ new_dft = [[] for i in range(next_ncol)]
+ root = self.root**next_ncol
+
+ # First half of next step
+ current_root = 1
+ for j in range(self.c_max_length // (next_ncol * 2)):
+ for i in range(next_ncol):
+ new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
+ current_root *= root
+ # Second half of next step
+ current_root = 1
+ for j in range(self.c_max_length // (next_ncol * 2)):
+ for i in range(next_ncol):
+ new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
+ current_root *= root
+ # Update
+ dft = new_dft
+ next_ncol = next_ncol // 2
+ return dft[0]
+
+ # multiply the DFTs of A and B and find A*B
+ def __multiply(self):
+ dft_a = self.__dft("A")
+ dft_b = self.__dft("B")
+ inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
+ del dft_a
+ del dft_b
+
+ # Corner Case
+ if len(inverce_c[0]) <= 1:
+ return inverce_c[0]
+ # Inverse DFT
+ next_ncol = 2
+ while next_ncol <= self.c_max_length:
+ new_inverse_c = [[] for i in range(next_ncol)]
+ root = self.root ** (next_ncol // 2)
+ current_root = 1
+ # First half of next step
+ for j in range(self.c_max_length // next_ncol):
+ for i in range(next_ncol // 2):
+ # Even positions
+ new_inverse_c[i].append(
+ (
+ inverce_c[i][j]
+ + inverce_c[i][j + self.c_max_length // next_ncol]
+ )
+ / 2
+ )
+ # Odd positions
+ new_inverse_c[i + next_ncol // 2].append(
+ (
+ inverce_c[i][j]
+ - inverce_c[i][j + self.c_max_length // next_ncol]
+ )
+ / (2 * current_root)
+ )
+ current_root *= root
+ # Update
+ inverce_c = new_inverse_c
+ next_ncol *= 2
+ # Unpack
+ inverce_c = [
+ complex(round(x[0].real, 8), round(x[0].imag, 8)) for x in inverce_c
+ ]
+
+ # Remove leading 0's
+ while inverce_c[-1] == 0:
+ inverce_c.pop()
+ return inverce_c
+
+ # Overwrite __str__ for print(); Shows A, B and A*B
+ def __str__(self):
+ a = "A = " + " + ".join(
+ f"{coef}*x^{i}" for i, coef in enumerate(self.polyA[: self.len_A])
+ )
+ b = "B = " + " + ".join(
+ f"{coef}*x^{i}" for i, coef in enumerate(self.polyB[: self.len_B])
+ )
+ c = "A*B = " + " + ".join(
+ f"{coef}*x^{i}" for i, coef in enumerate(self.product)
+ )
+
+ return f"{a}\n{b}\n{c}"
+
+
+# Unit tests
+if __name__ == "__main__":
+ import doctest
+
+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/radix2_fft.py |
Write clean docstrings for readability |
from __future__ import annotations
import math
from itertools import permutations
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(n: int = 7) -> int:
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
pandigitals = [num for num in perm_list if is_prime(num)]
return max(pandigitals) if pandigitals else 0
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,32 +1,77 @@-
-from __future__ import annotations
-
-import math
-from itertools import permutations
-
-
-def is_prime(number: int) -> bool:
-
- if 1 < number < 4:
- # 2 and 3 are primes
- return True
- elif number < 2 or number % 2 == 0 or number % 3 == 0:
- # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
- return False
-
- # All primes number are in format of 6k +/- 1
- for i in range(5, int(math.sqrt(number) + 1), 6):
- if number % i == 0 or number % (i + 2) == 0:
- return False
- return True
-
-
-def solution(n: int = 7) -> int:
- pandigital_str = "".join(str(i) for i in range(1, n + 1))
- perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
- pandigitals = [num for num in perm_list if is_prime(num)]
- return max(pandigitals) if pandigitals else 0
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Pandigital prime
+Problem 41: https://projecteuler.net/problem=41
+
+We shall say that an n-digit number is pandigital if it makes use of all the digits
+1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
+What is the largest n-digit pandigital prime that exists?
+
+All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
+So we will check only 7 digit pandigital numbers to obtain the largest possible
+pandigital prime.
+"""
+
+from __future__ import annotations
+
+import math
+from itertools import permutations
+
+
+def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(87)
+ False
+ >>> is_prime(563)
+ True
+ >>> is_prime(2999)
+ True
+ >>> is_prime(67483)
+ False
+ """
+
+ if 1 < number < 4:
+ # 2 and 3 are primes
+ return True
+ elif number < 2 or number % 2 == 0 or number % 3 == 0:
+ # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
+ return False
+
+ # All primes number are in format of 6k +/- 1
+ for i in range(5, int(math.sqrt(number) + 1), 6):
+ if number % i == 0 or number % (i + 2) == 0:
+ return False
+ return True
+
+
+def solution(n: int = 7) -> int:
+ """
+ Returns the maximum pandigital prime number of length n.
+ If there are none, then it will return 0.
+ >>> solution(2)
+ 0
+ >>> solution(4)
+ 4231
+ >>> solution(7)
+ 7652413
+ """
+ pandigital_str = "".join(str(i) for i in range(1, n + 1))
+ perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
+ pandigitals = [num for num in perm_list if is_prime(num)]
+ return max(pandigitals) if pandigitals else 0
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_041/sol1.py |
Write docstrings for data processing functions |
def is_geometric_series(series: list) -> bool:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
try:
common_ratio = series[1] / series[0]
for index in range(len(series) - 1):
if series[index + 1] / series[index] != common_ratio:
return False
except ZeroDivisionError:
return False
return True
def geometric_mean(series: list) -> float:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 1
for value in series:
answer *= value
return pow(answer, 1 / len(series))
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,32 @@+"""
+Geometric Mean
+Reference : https://en.wikipedia.org/wiki/Geometric_mean
+
+Geometric series
+Reference: https://en.wikipedia.org/wiki/Geometric_series
+"""
def is_geometric_series(series: list) -> bool:
+ """
+ checking whether the input series is geometric series or not
+ >>> is_geometric_series([2, 4, 8])
+ True
+ >>> is_geometric_series([3, 6, 12, 24])
+ True
+ >>> is_geometric_series([1, 2, 3])
+ False
+ >>> is_geometric_series([0, 0, 3])
+ False
+ >>> is_geometric_series([])
+ Traceback (most recent call last):
+ ...
+ ValueError: Input list must be a non empty list
+ >>> is_geometric_series(4)
+ Traceback (most recent call last):
+ ...
+ ValueError: Input series is not valid, valid series - [2, 4, 8]
+ """
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
@@ -18,6 +44,29 @@
def geometric_mean(series: list) -> float:
+ """
+ return the geometric mean of series
+
+ >>> geometric_mean([2, 4, 8])
+ 3.9999999999999996
+ >>> geometric_mean([3, 6, 12, 24])
+ 8.48528137423857
+ >>> geometric_mean([4, 8, 16])
+ 7.999999999999999
+ >>> geometric_mean(4)
+ Traceback (most recent call last):
+ ...
+ ValueError: Input series is not valid, valid series - [2, 4, 8]
+ >>> geometric_mean([1, 2, 3])
+ 1.8171205928321397
+ >>> geometric_mean([0, 2, 3])
+ 0.0
+ >>> geometric_mean([])
+ Traceback (most recent call last):
+ ...
+ ValueError: Input list must be a non empty list
+
+ """
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
@@ -31,4 +80,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/geometric.py |
Add docstrings to clarify complex logic |
from __future__ import annotations
def is_9_pandigital(n: int) -> bool:
s = str(n)
return len(s) == 9 and set(s) == set("123456789")
def solution() -> int | None:
for base_num in range(9999, 4999, -1):
candidate = 100002 * base_num
if is_9_pandigital(candidate):
return candidate
for base_num in range(333, 99, -1):
candidate = 1002003 * base_num
if is_9_pandigital(candidate):
return candidate
return None
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,13 +1,65 @@+"""
+Project Euler Problem 38: https://projecteuler.net/problem=38
+
+Take the number 192 and multiply it by each of 1, 2, and 3:
+
+192 x 1 = 192
+192 x 2 = 384
+192 x 3 = 576
+
+By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call
+192384576 the concatenated product of 192 and (1,2,3)
+
+The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5,
+giving the pandigital, 918273645, which is the concatenated product of 9 and
+(1,2,3,4,5).
+
+What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
+concatenated product of an integer with (1,2, ... , n) where n > 1?
+
+Solution:
+Since n>1, the largest candidate for the solution will be a concactenation of
+a 4-digit number and its double, a 5-digit number.
+Let a be the 4-digit number.
+a has 4 digits => 1000 <= a < 10000
+2a has 5 digits => 10000 <= 2a < 100000
+=> 5000 <= a < 10000
+
+The concatenation of a with 2a = a * 10^5 + 2a
+so our candidate for a given a is 100002 * a.
+We iterate through the search space 5000 <= a < 10000 in reverse order,
+calculating the candidates for each a and checking if they are 1-9 pandigital.
+
+In case there are no 4-digit numbers that satisfy this property, we check
+the 3-digit numbers with a similar formula (the example a=192 gives a lower
+bound on the length of a):
+a has 3 digits, etc...
+=> 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a
+ = 1002003 * a
+"""
from __future__ import annotations
def is_9_pandigital(n: int) -> bool:
+ """
+ Checks whether n is a 9-digit 1 to 9 pandigital number.
+ >>> is_9_pandigital(12345)
+ False
+ >>> is_9_pandigital(156284973)
+ True
+ >>> is_9_pandigital(1562849733)
+ False
+ """
s = str(n)
return len(s) == 9 and set(s) == set("123456789")
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.
+ """
for base_num in range(9999, 4999, -1):
candidate = 100002 * base_num
if is_9_pandigital(candidate):
@@ -22,4 +74,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_038/sol1.py |
Create documentation strings for testing functions |
from __future__ import annotations
def is_palindrome(n: int | str) -> bool:
n = str(n)
return n == n[::-1]
def solution(n: int = 1000000):
total = 0
for i in range(1, n):
if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip())))) | --- +++ @@ -1,13 +1,62 @@+"""
+Project Euler Problem 36
+https://projecteuler.net/problem=36
+
+Problem Statement:
+
+Double-base palindromes
+Problem 36
+The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
+
+Find the sum of all numbers, less than one million, which are palindromic in
+base 10 and base 2.
+
+(Please note that the palindromic number, in either base, may not include
+leading zeros.)
+"""
from __future__ import annotations
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.
+
+ >>> is_palindrome(909)
+ True
+ >>> is_palindrome(908)
+ False
+ >>> is_palindrome('10101')
+ True
+ >>> is_palindrome('10111')
+ False
+ """
n = str(n)
return n == n[::-1]
def solution(n: int = 1000000):
+ """Return the sum of all numbers, less than n , which are palindromic in
+ base 10 and base 2.
+
+ >>> solution(1000000)
+ 872187
+ >>> solution(500000)
+ 286602
+ >>> solution(100000)
+ 286602
+ >>> solution(1000)
+ 1772
+ >>> solution(100)
+ 157
+ >>> solution(10)
+ 25
+ >>> solution(2)
+ 1
+ >>> solution(1)
+ 0
+ """
total = 0
for i in range(1, n):
@@ -17,4 +66,4 @@
if __name__ == "__main__":
- print(solution(int(str(input().strip()))))+ print(solution(int(str(input().strip()))))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_036/sol1.py |
Document my Python code with docstrings |
from __future__ import annotations
import typing
from collections import Counter
def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]:
triplets: typing.Counter[int] = Counter()
for base in range(1, max_perimeter + 1):
for perpendicular in range(base, max_perimeter + 1):
hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5
if hypotenuse == int(hypotenuse):
perimeter = int(base + perpendicular + hypotenuse)
if perimeter > max_perimeter:
continue
triplets[perimeter] += 1
return triplets
def solution(n: int = 1000) -> int:
triplets = pythagorean_triple(n)
return triplets.most_common(1)[0][0]
if __name__ == "__main__":
print(f"Perimeter {solution()} has maximum solutions") | --- +++ @@ -1,27 +1,55 @@-
-from __future__ import annotations
-
-import typing
-from collections import Counter
-
-
-def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]:
- triplets: typing.Counter[int] = Counter()
- for base in range(1, max_perimeter + 1):
- for perpendicular in range(base, max_perimeter + 1):
- hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5
- if hypotenuse == int(hypotenuse):
- perimeter = int(base + perpendicular + hypotenuse)
- if perimeter > max_perimeter:
- continue
- triplets[perimeter] += 1
- return triplets
-
-
-def solution(n: int = 1000) -> int:
- triplets = pythagorean_triple(n)
- return triplets.most_common(1)[0][0]
-
-
-if __name__ == "__main__":
- print(f"Perimeter {solution()} has maximum solutions")+"""
+Problem 39: https://projecteuler.net/problem=39
+
+If p is the perimeter of a right angle triangle with integral length sides,
+{a,b,c}, there are exactly three solutions for p = 120.
+{20,48,52}, {24,45,51}, {30,40,50}
+
+For which value of p ≤ 1000, is the number of solutions maximised?
+"""
+
+from __future__ import annotations
+
+import typing
+from collections import Counter
+
+
+def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]:
+ """
+ Returns a dictionary with keys as the perimeter of a right angled triangle
+ and value as the number of corresponding triplets.
+ >>> pythagorean_triple(15)
+ Counter({12: 1})
+ >>> pythagorean_triple(40)
+ Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1})
+ >>> pythagorean_triple(50)
+ Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1})
+ """
+ triplets: typing.Counter[int] = Counter()
+ for base in range(1, max_perimeter + 1):
+ for perpendicular in range(base, max_perimeter + 1):
+ hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5
+ if hypotenuse == int(hypotenuse):
+ perimeter = int(base + perpendicular + hypotenuse)
+ if perimeter > max_perimeter:
+ continue
+ triplets[perimeter] += 1
+ return triplets
+
+
+def solution(n: int = 1000) -> int:
+ """
+ Returns perimeter with maximum solutions.
+ >>> solution(100)
+ 90
+ >>> solution(200)
+ 180
+ >>> solution(1000)
+ 840
+ """
+ triplets = pythagorean_triple(n)
+ return triplets.most_common(1)[0][0]
+
+
+if __name__ == "__main__":
+ print(f"Perimeter {solution()} has maximum solutions")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_039/sol1.py |
Provide docstrings following PEP 257 |
def hexagonal_num(n: int) -> int:
return n * (2 * n - 1)
def is_pentagonal(n: int) -> bool:
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(start: int = 144) -> int:
n = start
num = hexagonal_num(n)
while not is_pentagonal(num):
n += 1
num = hexagonal_num(n)
return num
if __name__ == "__main__":
print(f"{solution()} = ") | --- +++ @@ -1,22 +1,59 @@-
-
-def hexagonal_num(n: int) -> int:
- return n * (2 * n - 1)
-
-
-def is_pentagonal(n: int) -> bool:
- root = (1 + 24 * n) ** 0.5
- return ((1 + root) / 6) % 1 == 0
-
-
-def solution(start: int = 144) -> int:
- n = start
- num = hexagonal_num(n)
- while not is_pentagonal(num):
- n += 1
- num = hexagonal_num(n)
- return num
-
-
-if __name__ == "__main__":
- print(f"{solution()} = ")+"""
+Problem 45: https://projecteuler.net/problem=45
+
+Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
+Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ...
+Pentagonal P(n) = (n * (3 * n - 1)) / 2 1, 5, 12, 22, 35, ...
+Hexagonal H(n) = n * (2 * n - 1) 1, 6, 15, 28, 45, ...
+It can be verified that T(285) = P(165) = H(143) = 40755.
+
+Find the next triangle number that is also pentagonal and hexagonal.
+All triangle numbers are hexagonal numbers.
+T(2n-1) = n * (2 * n - 1) = H(n)
+So we shall check only for hexagonal numbers which are also pentagonal.
+"""
+
+
+def hexagonal_num(n: int) -> int:
+ """
+ Returns nth hexagonal number
+ >>> hexagonal_num(143)
+ 40755
+ >>> hexagonal_num(21)
+ 861
+ >>> hexagonal_num(10)
+ 190
+ """
+ return n * (2 * n - 1)
+
+
+def is_pentagonal(n: int) -> bool:
+ """
+ Returns True if n is pentagonal, False otherwise.
+ >>> is_pentagonal(330)
+ True
+ >>> is_pentagonal(7683)
+ False
+ >>> is_pentagonal(2380)
+ True
+ """
+ root = (1 + 24 * n) ** 0.5
+ return ((1 + root) / 6) % 1 == 0
+
+
+def solution(start: int = 144) -> int:
+ """
+ Returns the next number which is triangular, pentagonal and hexagonal.
+ >>> solution(144)
+ 1533776805
+ """
+ n = start
+ num = hexagonal_num(n)
+ while not is_pentagonal(num):
+ n += 1
+ num = hexagonal_num(n)
+ return num
+
+
+if __name__ == "__main__":
+ print(f"{solution()} = ")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_045/sol1.py |
Add inline docstrings for readability |
def is_pentagonal(n: int) -> bool:
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(limit: int = 5000) -> int:
pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
for i, pentagonal_i in enumerate(pentagonal_nums):
for j in range(i, len(pentagonal_nums)):
pentagonal_j = pentagonal_nums[j]
a = pentagonal_i + pentagonal_j
b = pentagonal_j - pentagonal_i
if is_pentagonal(a) and is_pentagonal(b):
return b
return -1
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,22 +1,49 @@-
-
-def is_pentagonal(n: int) -> bool:
- root = (1 + 24 * n) ** 0.5
- return ((1 + root) / 6) % 1 == 0
-
-
-def solution(limit: int = 5000) -> int:
- pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
- for i, pentagonal_i in enumerate(pentagonal_nums):
- for j in range(i, len(pentagonal_nums)):
- pentagonal_j = pentagonal_nums[j]
- a = pentagonal_i + pentagonal_j
- b = pentagonal_j - pentagonal_i
- if is_pentagonal(a) and is_pentagonal(b):
- return b
-
- return -1
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Problem 44: https://projecteuler.net/problem=44
+
+Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The first ten
+pentagonal numbers are:
+1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
+It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
+70 - 22 = 48, is not pentagonal.
+
+Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference
+are pentagonal and D = |Pk - Pj| is minimised; what is the value of D?
+"""
+
+
+def is_pentagonal(n: int) -> bool:
+ """
+ Returns True if n is pentagonal, False otherwise.
+ >>> is_pentagonal(330)
+ True
+ >>> is_pentagonal(7683)
+ False
+ >>> is_pentagonal(2380)
+ True
+ """
+ root = (1 + 24 * n) ** 0.5
+ return ((1 + root) / 6) % 1 == 0
+
+
+def solution(limit: int = 5000) -> int:
+ """
+ Returns the minimum difference of two pentagonal numbers P1 and P2 such that
+ P1 + P2 is pentagonal and P2 - P1 is pentagonal.
+ >>> solution(5000)
+ 5482660
+ """
+ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
+ for i, pentagonal_i in enumerate(pentagonal_nums):
+ for j in range(i, len(pentagonal_nums)):
+ pentagonal_j = pentagonal_nums[j]
+ a = pentagonal_i + pentagonal_j
+ b = pentagonal_j - pentagonal_i
+ if is_pentagonal(a) and is_pentagonal(b):
+ return b
+
+ return -1
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_044/sol1.py |
Auto-generate documentation strings for this file |
import math
from itertools import permutations
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def search(target: int, prime_list: list) -> bool:
left, right = 0, len(prime_list) - 1
while left <= right:
middle = (left + right) // 2
if prime_list[middle] == target:
return True
elif prime_list[middle] < target:
left = middle + 1
else:
right = middle - 1
return False
def solution():
prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)]
candidates = []
for number in prime_list:
tmp_numbers = []
for prime_member in permutations(list(str(number))):
prime = int("".join(prime_member))
if prime % 2 == 0:
continue
if search(prime, prime_list):
tmp_numbers.append(prime)
tmp_numbers.sort()
if len(tmp_numbers) >= 3:
candidates.append(tmp_numbers)
passed = []
for candidate in candidates:
length = len(candidate)
found = False
for i in range(length):
for j in range(i + 1, length):
for k in range(j + 1, length):
if (
abs(candidate[i] - candidate[j])
== abs(candidate[j] - candidate[k])
and len({candidate[i], candidate[j], candidate[k]}) == 3
):
passed.append(
sorted([candidate[i], candidate[j], candidate[k]])
)
found = True
if found:
break
if found:
break
if found:
break
answer = set()
for seq in passed:
answer.add("".join([str(i) for i in seq]))
return max(int(x) for x in answer)
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,9 +1,58 @@+"""
+Prime permutations
+
+Problem 49
+
+The arithmetic sequence, 1487, 4817, 8147, in which each of
+the terms increases by 3330, is unusual in two ways:
+(i) each of the three terms are prime,
+(ii) each of the 4-digit numbers are permutations of one another.
+
+There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
+exhibiting this property, but there is one other 4-digit increasing sequence.
+
+What 12-digit number do you form by concatenating the three terms in this sequence?
+
+Solution:
+
+First, we need to generate all 4 digits prime numbers. Then greedy
+all of them and use permutation to form new numbers. Use binary search
+to check if the permutated numbers is in our prime list and include
+them in a candidate list.
+
+After that, bruteforce all passed candidates sequences using
+3 nested loops since we know the answer will be 12 digits.
+The bruteforce of this solution will be about 1 sec.
+"""
import math
from itertools import permutations
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(87)
+ False
+ >>> is_prime(563)
+ True
+ >>> is_prime(2999)
+ True
+ >>> is_prime(67483)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -20,6 +69,15 @@
def search(target: int, prime_list: list) -> bool:
+ """
+ function to search a number in a list using Binary Search.
+ >>> search(3, [1, 2, 3])
+ True
+ >>> search(4, [1, 2, 3])
+ False
+ >>> search(101, list(range(-100, 100)))
+ False
+ """
left, right = 0, len(prime_list) - 1
while left <= right:
@@ -35,6 +93,11 @@
def solution():
+ """
+ Return the solution of the problem.
+ >>> solution()
+ 296962999629
+ """
prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)]
candidates = []
@@ -87,4 +150,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_049/sol1.py |
Generate missing documentation strings |
from itertools import permutations
def is_substring_divisible(num: tuple) -> bool:
if num[3] % 2 != 0:
return False
if (num[2] + num[3] + num[4]) % 3 != 0:
return False
if num[5] % 5 != 0:
return False
tests = [7, 11, 13, 17]
for i, test in enumerate(tests):
if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True
def solution(n: int = 10) -> int:
return sum(
int("".join(map(str, num)))
for num in permutations(range(n))
if is_substring_divisible(num)
)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,31 +1,66 @@-
-from itertools import permutations
-
-
-def is_substring_divisible(num: tuple) -> bool:
- if num[3] % 2 != 0:
- return False
-
- if (num[2] + num[3] + num[4]) % 3 != 0:
- return False
-
- if num[5] % 5 != 0:
- return False
-
- tests = [7, 11, 13, 17]
- for i, test in enumerate(tests):
- if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
- return False
- return True
-
-
-def solution(n: int = 10) -> int:
- return sum(
- int("".join(map(str, num)))
- for num in permutations(range(n))
- if is_substring_divisible(num)
- )
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Problem 43: https://projecteuler.net/problem=43
+
+The number, 1406357289, is a 0 to 9 pandigital number because it is made up of
+each of the digits 0 to 9 in some order, but it also has a rather interesting
+sub-string divisibility property.
+
+Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note
+the following:
+
+d2d3d4=406 is divisible by 2
+d3d4d5=063 is divisible by 3
+d4d5d6=635 is divisible by 5
+d5d6d7=357 is divisible by 7
+d6d7d8=572 is divisible by 11
+d7d8d9=728 is divisible by 13
+d8d9d10=289 is divisible by 17
+Find the sum of all 0 to 9 pandigital numbers with this property.
+"""
+
+from itertools import permutations
+
+
+def is_substring_divisible(num: tuple) -> bool:
+ """
+ Returns True if the pandigital number passes
+ all the divisibility tests.
+ >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9))
+ False
+ >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9))
+ False
+ >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9))
+ True
+ """
+ if num[3] % 2 != 0:
+ return False
+
+ if (num[2] + num[3] + num[4]) % 3 != 0:
+ return False
+
+ if num[5] % 5 != 0:
+ return False
+
+ tests = [7, 11, 13, 17]
+ for i, test in enumerate(tests):
+ if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
+ return False
+ return True
+
+
+def solution(n: int = 10) -> int:
+ """
+ Returns the sum of all pandigital numbers which pass the
+ divisibility tests.
+ >>> solution(10)
+ 16695334890
+ """
+ return sum(
+ int("".join(map(str, num)))
+ for num in permutations(range(n))
+ if is_substring_divisible(num)
+ )
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_043/sol1.py |
Add docstrings that explain inputs and outputs |
from __future__ import annotations
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)]
def compute_nums(n: int) -> list[int]:
if not isinstance(n, int):
raise ValueError("n must be an integer")
if n <= 0:
raise ValueError("n must be >= 0")
list_nums = []
for num in range(len(odd_composites)):
i = 0
while 2 * i * i <= odd_composites[num]:
rem = odd_composites[num] - 2 * i * i
if is_prime(rem):
break
i += 1
else:
list_nums.append(odd_composites[num])
if len(list_nums) == n:
return list_nums
return []
def solution() -> int:
return compute_nums(1)[0]
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,53 +1,116 @@-
-from __future__ import annotations
-
-import math
-
-
-def is_prime(number: int) -> bool:
-
- if 1 < number < 4:
- # 2 and 3 are primes
- return True
- elif number < 2 or number % 2 == 0 or number % 3 == 0:
- # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
- return False
-
- # All primes number are in format of 6k +/- 1
- for i in range(5, int(math.sqrt(number) + 1), 6):
- if number % i == 0 or number % (i + 2) == 0:
- return False
- return True
-
-
-odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)]
-
-
-def compute_nums(n: int) -> list[int]:
- if not isinstance(n, int):
- raise ValueError("n must be an integer")
- if n <= 0:
- raise ValueError("n must be >= 0")
-
- list_nums = []
- for num in range(len(odd_composites)):
- i = 0
- while 2 * i * i <= odd_composites[num]:
- rem = odd_composites[num] - 2 * i * i
- if is_prime(rem):
- break
- i += 1
- else:
- list_nums.append(odd_composites[num])
- if len(list_nums) == n:
- return list_nums
-
- return []
-
-
-def solution() -> int:
- return compute_nums(1)[0]
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Problem 46: https://projecteuler.net/problem=46
+
+It was proposed by Christian Goldbach that every odd composite number can be
+written as the sum of a prime and twice a square.
+
+9 = 7 + 2 x 12
+15 = 7 + 2 x 22
+21 = 3 + 2 x 32
+25 = 7 + 2 x 32
+27 = 19 + 2 x 22
+33 = 31 + 2 x 12
+
+It turns out that the conjecture was false.
+
+What is the smallest odd composite that cannot be written as the sum of a
+prime and twice a square?
+"""
+
+from __future__ import annotations
+
+import math
+
+
+def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(87)
+ False
+ >>> is_prime(563)
+ True
+ >>> is_prime(2999)
+ True
+ >>> is_prime(67483)
+ False
+ """
+
+ if 1 < number < 4:
+ # 2 and 3 are primes
+ return True
+ elif number < 2 or number % 2 == 0 or number % 3 == 0:
+ # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
+ return False
+
+ # All primes number are in format of 6k +/- 1
+ for i in range(5, int(math.sqrt(number) + 1), 6):
+ if number % i == 0 or number % (i + 2) == 0:
+ return False
+ return True
+
+
+odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)]
+
+
+def compute_nums(n: int) -> list[int]:
+ """
+ Returns a list of first n odd composite numbers which do
+ not follow the conjecture.
+ >>> compute_nums(1)
+ [5777]
+ >>> compute_nums(2)
+ [5777, 5993]
+ >>> compute_nums(0)
+ Traceback (most recent call last):
+ ...
+ ValueError: n must be >= 0
+ >>> compute_nums("a")
+ Traceback (most recent call last):
+ ...
+ ValueError: n must be an integer
+ >>> compute_nums(1.1)
+ Traceback (most recent call last):
+ ...
+ ValueError: n must be an integer
+
+ """
+ if not isinstance(n, int):
+ raise ValueError("n must be an integer")
+ if n <= 0:
+ raise ValueError("n must be >= 0")
+
+ list_nums = []
+ for num in range(len(odd_composites)):
+ i = 0
+ while 2 * i * i <= odd_composites[num]:
+ rem = odd_composites[num] - 2 * i * i
+ if is_prime(rem):
+ break
+ i += 1
+ else:
+ list_nums.append(odd_composites[num])
+ if len(list_nums) == n:
+ return list_nums
+
+ return []
+
+
+def solution() -> int:
+ """Return the solution to the problem"""
+ return compute_nums(1)[0]
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_046/sol1.py |
Add structured docstrings to improve clarity |
from __future__ import annotations
def prime_sieve(limit: int) -> list[int]:
is_prime = [True] * limit
is_prime[0] = False
is_prime[1] = False
is_prime[2] = True
for i in range(3, int(limit**0.5 + 1), 2):
index = i * 2
while index < limit:
is_prime[index] = False
index = index + i
primes = [2]
for i in range(3, limit, 2):
if is_prime[i]:
primes.append(i)
return primes
def solution(ceiling: int = 1_000_000) -> int:
primes = prime_sieve(ceiling)
length = 0
largest = 0
for i in range(len(primes)):
for j in range(i + length, len(primes)):
sol = sum(primes[i:j])
if sol >= ceiling:
break
if sol in primes:
length = j - i
largest = sol
return largest
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,36 @@+"""
+Project Euler Problem 50: https://projecteuler.net/problem=50
+
+Consecutive prime sum
+
+The prime 41, can be written as the sum of six consecutive primes:
+41 = 2 + 3 + 5 + 7 + 11 + 13
+
+This is the longest sum of consecutive primes that adds to a prime below
+one-hundred.
+
+The longest sum of consecutive primes below one-thousand that adds to a prime,
+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 __future__ import annotations
def prime_sieve(limit: int) -> list[int]:
+ """
+ Sieve of Erotosthenes
+ Function to return all the prime numbers up to a number 'limit'
+ https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
+
+ >>> prime_sieve(3)
+ [2]
+
+ >>> prime_sieve(50)
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
+ """
is_prime = [True] * limit
is_prime[0] = False
is_prime[1] = False
@@ -24,6 +52,19 @@
def solution(ceiling: int = 1_000_000) -> int:
+ """
+ Returns the biggest prime, below the celing, that can be written as the sum
+ of consecutive the most consecutive primes.
+
+ >>> solution(500)
+ 499
+
+ >>> solution(1_000)
+ 953
+
+ >>> solution(10_000)
+ 9521
+ """
primes = prime_sieve(ceiling)
length = 0
largest = 0
@@ -42,4 +83,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_050/sol1.py |
Add detailed documentation for each class |
from __future__ import annotations
from collections import Counter
def prime_sieve(n: int) -> list[int]:
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
is_prime[2] = True
for i in range(3, int(n**0.5 + 1), 2):
index = i * 2
while index < n:
is_prime[index] = False
index = index + i
primes = [2]
for i in range(3, n, 2):
if is_prime[i]:
primes.append(i)
return primes
def digit_replacements(number: int) -> list[list[int]]:
number_str = str(number)
replacements = []
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for duplicate in Counter(number_str) - Counter(set(number_str)):
family = [int(number_str.replace(duplicate, digit)) for digit in digits]
replacements.append(family)
return replacements
def solution(family_length: int = 8) -> int:
numbers_checked = set()
# Filter primes with less than 3 replaceable digits
primes = {
x for x in set(prime_sieve(1_000_000)) if len(str(x)) - len(set(str(x))) >= 3
}
for prime in primes:
if prime in numbers_checked:
continue
replacements = digit_replacements(prime)
for family in replacements:
numbers_checked.update(family)
primes_in_family = primes.intersection(family)
if len(primes_in_family) != family_length:
continue
return min(primes_in_family)
return -1
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,20 @@+"""
+https://projecteuler.net/problem=51
+Prime digit replacements
+Problem 51
+
+By replacing the 1st digit of the 2-digit number *3, it turns out that six of
+the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
+
+By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
+number is the first example having seven primes among the ten generated numbers,
+yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
+Consequently 56003, being the first member of this family, is the smallest prime
+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
@@ -5,6 +22,17 @@
def prime_sieve(n: int) -> list[int]:
+ """
+ Sieve of Erotosthenes
+ Function to return all the prime numbers up to a certain number
+ https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
+
+ >>> prime_sieve(3)
+ [2]
+
+ >>> prime_sieve(50)
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
+ """
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
@@ -26,6 +54,16 @@
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
+
+ >>> digit_replacements(544)
+ [[500, 511, 522, 533, 544, 555, 566, 577, 588, 599]]
+
+ >>> digit_replacements(3112)
+ [[3002, 3112, 3222, 3332, 3442, 3552, 3662, 3772, 3882, 3992]]
+ """
number_str = str(number)
replacements = []
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
@@ -38,6 +76,15 @@
def solution(family_length: int = 8) -> int:
+ """
+ Returns the solution of the problem
+
+ >>> solution(2)
+ 229399
+
+ >>> solution(3)
+ 221311
+ """
numbers_checked = set()
# Filter primes with less than 3 replaceable digits
@@ -64,4 +111,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_051/sol1.py |
Create structured documentation for my script |
from math import factorial
def combinations(n, r):
return factorial(n) / (factorial(r) * factorial(n - r))
def solution():
total = 0
for i in range(1, 101):
for j in range(1, i + 1):
if combinations(i, j) > 1e6:
total += 1
return total
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,3 +1,21 @@+"""
+Combinatoric selections
+Problem 53
+
+There are exactly ten ways of selecting three from five, 12345:
+
+ 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
+
+In combinatorics, we use the notation, 5C3 = 10.
+
+In general,
+
+nCr = n!/(r!(n-r)!),where r ≤ n, n! = nx(n-1)x...x3x2x1, and 0! = 1.
+It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
+
+How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater
+than one-million?
+"""
from math import factorial
@@ -7,6 +25,12 @@
def solution():
+ """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than
+ one-million
+
+ >>> solution()
+ 4075
+ """
total = 0
for i in range(1, 101):
@@ -17,4 +41,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_053/sol1.py |
Replace inline comments with docstrings |
def is_palindrome(n: int) -> bool:
return str(n) == str(n)[::-1]
def sum_reverse(n: int) -> int:
return int(n) + int(str(n)[::-1])
def solution(limit: int = 10000) -> int:
lychrel_nums = []
for num in range(1, limit):
iterations = 0
a = num
while iterations < 50:
num = sum_reverse(num)
iterations += 1
if is_palindrome(num):
break
else:
lychrel_nums.append(a)
return len(lychrel_nums)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,27 +1,81 @@-
-
-def is_palindrome(n: int) -> bool:
- return str(n) == str(n)[::-1]
-
-
-def sum_reverse(n: int) -> int:
- return int(n) + int(str(n)[::-1])
-
-
-def solution(limit: int = 10000) -> int:
- lychrel_nums = []
- for num in range(1, limit):
- iterations = 0
- a = num
- while iterations < 50:
- num = sum_reverse(num)
- iterations += 1
- if is_palindrome(num):
- break
- else:
- lychrel_nums.append(a)
- return len(lychrel_nums)
-
-
-if __name__ == "__main__":
- print(f"{solution() = }")+"""
+Lychrel numbers
+Problem 55: https://projecteuler.net/problem=55
+
+If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
+
+Not all numbers produce palindromes so quickly. For example,
+349 + 943 = 1292,
+1292 + 2921 = 4213
+4213 + 3124 = 7337
+That is, 349 took three iterations to arrive at a palindrome.
+
+Although no one has proved it yet, it is thought that some numbers, like 196,
+never produce a palindrome. A number that never forms a palindrome through the
+reverse and add process is called a Lychrel number. Due to the theoretical nature
+of these numbers, and for the purpose of this problem, we shall assume that a number
+is Lychrel until proven otherwise. In addition you are given that for every number
+below ten-thousand, it will either (i) become a palindrome in less than fifty
+iterations, or, (ii) no one, with all the computing power that exists, has managed
+so far to map it to a palindrome. In fact, 10677 is the first number to be shown
+to require over fifty iterations before producing a palindrome:
+4668731596684224866951378664 (53 iterations, 28-digits).
+
+Surprisingly, there are palindromic numbers that are themselves Lychrel numbers;
+the first example is 4994.
+How many Lychrel numbers are there below ten-thousand?
+"""
+
+
+def is_palindrome(n: int) -> bool:
+ """
+ Returns True if a number is palindrome.
+ >>> is_palindrome(12567321)
+ False
+ >>> is_palindrome(1221)
+ True
+ >>> is_palindrome(9876789)
+ True
+ """
+ return str(n) == str(n)[::-1]
+
+
+def sum_reverse(n: int) -> int:
+ """
+ Returns the sum of n and reverse of n.
+ >>> sum_reverse(123)
+ 444
+ >>> sum_reverse(3478)
+ 12221
+ >>> sum_reverse(12)
+ 33
+ """
+ return int(n) + int(str(n)[::-1])
+
+
+def solution(limit: int = 10000) -> int:
+ """
+ Returns the count of all lychrel numbers below limit.
+ >>> solution(10000)
+ 249
+ >>> solution(5000)
+ 76
+ >>> solution(1000)
+ 13
+ """
+ lychrel_nums = []
+ for num in range(1, limit):
+ iterations = 0
+ a = num
+ while iterations < 50:
+ num = sum_reverse(num)
+ iterations += 1
+ if is_palindrome(num):
+ break
+ else:
+ lychrel_nums.append(a)
+ return len(lychrel_nums)
+
+
+if __name__ == "__main__":
+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_055/sol1.py |
Help me add docstrings to my project |
from collections import defaultdict
def solution(max_base: int = 5) -> int:
freqs = defaultdict(list)
num = 0
while True:
digits = get_digits(num)
freqs[digits].append(num)
if len(freqs[digits]) == max_base:
base = freqs[digits][0] ** 3
return base
num += 1
def get_digits(num: int) -> str:
return "".join(sorted(str(num**3)))
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,8 +1,35 @@+"""
+Project Euler 62
+https://projecteuler.net/problem=62
+
+The cube, 41063625 (345^3), can be permuted to produce two other cubes:
+56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube
+which has exactly three permutations of its digits which are also cube.
+
+Find the smallest cube for which exactly five permutations of its digits are
+cube.
+"""
from collections import defaultdict
def solution(max_base: int = 5) -> int:
+ """
+ Iterate through every possible cube and sort the cube's digits in
+ ascending order. Sorting maintains an ordering of the digits that allows
+ you to compare permutations. Store each sorted sequence of digits in a
+ dictionary, whose key is the sequence of digits and value is a list of
+ numbers that are the base of the cube.
+
+ Once you find 5 numbers that produce the same sequence of digits, return
+ the smallest one, which is at index 0 since we insert each base number in
+ ascending order.
+
+ >>> solution(2)
+ 125
+ >>> solution(3)
+ 41063625
+ """
freqs = defaultdict(list)
num = 0
@@ -18,8 +45,18 @@
def get_digits(num: int) -> str:
+ """
+ Computes the sorted sequence of digits of the cube of num.
+
+ >>> get_digits(3)
+ '27'
+ >>> get_digits(99)
+ '027999'
+ >>> get_digits(123)
+ '0166788'
+ """
return "".join(sorted(str(num**3)))
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_062/sol1.py |
Document this module using docstrings |
def solution():
i = 1
while True:
if (
sorted(str(i))
== sorted(str(2 * i))
== sorted(str(3 * i))
== sorted(str(4 * i))
== sorted(str(5 * i))
== sorted(str(6 * i))
):
return i
i += 1
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,22 @@+"""
+Permuted multiples
+Problem 52
+
+It can be seen that the number, 125874, and its double, 251748, contain exactly
+the same digits, but in a different order.
+
+Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x,
+contain the same digits.
+"""
def solution():
+ """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and
+ 6x, contain the same digits.
+
+ >>> solution()
+ 142857
+ """
i = 1
while True:
@@ -18,4 +34,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_052/sol1.py |
Provide docstrings following PEP 257 |
import math
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(ratio: float = 0.1) -> int:
j = 3
primes = 3
while primes / (2 * j - 1) >= ratio:
for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1):
primes += is_prime(i)
j += 2
return j
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,8 +1,66 @@+"""
+Project Euler Problem 58:https://projecteuler.net/problem=58
+
+
+Starting with 1 and spiralling anticlockwise in the following way,
+a square spiral with side length 7 is formed.
+
+37 36 35 34 33 32 31
+38 17 16 15 14 13 30
+39 18 5 4 3 12 29
+40 19 6 1 2 11 28
+41 20 7 8 9 10 27
+42 21 22 23 24 25 26
+43 44 45 46 47 48 49
+
+It is interesting to note that the odd squares lie along the bottom right
+diagonal ,but what is more interesting is that 8 out of the 13 numbers
+lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
+
+If one complete new layer is wrapped around the spiral above,
+a square spiral with side length 9 will be formed.
+If this process is continued,
+what is the side length of the square spiral for which
+the ratio of primes along both diagonals first falls below 10%?
+
+Solution: We have to find an odd length side for which square falls below
+10%. With every layer we add 4 elements are being added to the diagonals
+,lets say we have a square spiral of odd length with side length j,
+then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1)
+j*j+4*(j+1). Out of these 4 only the first three can become prime
+because last one reduces to (j+2)*(j+2).
+So we check individually each one of these before incrementing our
+count of current primes.
+
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ >>> is_prime(1)
+ False
+ >>> is_prime(2)
+ True
+ >>> is_prime(3)
+ True
+ >>> is_prime(27)
+ False
+ >>> is_prime(87)
+ False
+ >>> is_prime(563)
+ True
+ >>> is_prime(2999)
+ True
+ >>> is_prime(67483)
+ False
+ """
if 1 < number < 4:
# 2 and 3 are primes
@@ -19,6 +77,17 @@
def solution(ratio: float = 0.1) -> int:
+ """
+ Returns the side length of the square spiral of odd length greater
+ than 1 for which the ratio of primes along both diagonals
+ first falls below the given ratio.
+ >>> solution(.5)
+ 11
+ >>> solution(.2)
+ 309
+ >>> solution(.111)
+ 11317
+ """
j = 3
primes = 3
@@ -33,4 +102,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_058/sol1.py |
Replace inline comments with docstrings |
def solution():
total = 0
for i in range(1, 1001):
total += i**i
return str(total)[-10:]
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,20 @@+"""
+Self Powers
+Problem 48
+
+The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
+
+Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
+"""
def solution():
+ """
+ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
+
+ >>> solution()
+ '9110846700'
+ """
total = 0
for i in range(1, 1001):
total += i**i
@@ -8,4 +22,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_048/sol1.py |
Add standardized docstrings across the file |
def solution(n: int = 1000) -> int:
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
numerator = prev_numerator + 2 * prev_denominator
denominator = prev_numerator + prev_denominator
if len(str(numerator)) > len(str(denominator)):
result.append(i)
prev_numerator = numerator
prev_denominator = denominator
return len(result)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,36 @@+"""
+Project Euler Problem 57: https://projecteuler.net/problem=57
+It is possible to show that the square root of two can be expressed as an infinite
+continued fraction.
+
+sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))
+
+By expanding this for the first four iterations, we get:
+1 + 1 / 2 = 3 / 2 = 1.5
+1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
+1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
+1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...
+
+The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
+1393/985, is the first example where the number of digits in the numerator exceeds
+the number of digits in the denominator.
+
+In the first one-thousand expansions, how many fractions contain a numerator with
+more digits than the denominator?
+"""
def solution(n: int = 1000) -> int:
+ """
+ returns number of fractions containing a numerator with more digits than
+ the denominator in the first n expansions.
+ >>> solution(14)
+ 2
+ >>> solution(100)
+ 15
+ >>> solution(10000)
+ 1508
+ """
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
@@ -15,4 +45,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_057/sol1.py |
Add concise docstrings to each method |
from __future__ import annotations
import os
class PokerHand:
_HAND_NAME = (
"High card",
"One pair",
"Two pairs",
"Three of a kind",
"Straight",
"Flush",
"Full house",
"Four of a kind",
"Straight flush",
"Royal flush",
)
_CARD_NAME = (
"", # placeholder as tuples are zero-indexed
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Jack",
"Queen",
"King",
"Ace",
)
def __init__(self, hand: str) -> None:
if not isinstance(hand, str):
msg = f"Hand should be of type 'str': {hand!r}"
raise TypeError(msg)
# split removes duplicate whitespaces so no need of strip
if len(hand.split(" ")) != 5:
msg = f"Hand should contain only 5 cards: {hand!r}"
raise ValueError(msg)
self._hand = hand
self._first_pair = 0
self._second_pair = 0
self._card_values, self._card_suit = self._internal_state()
self._hand_type = self._get_hand_type()
self._high_card = self._card_values[0]
@property
def hand(self):
return self._hand
def compare_with(self, other: PokerHand) -> str:
# Breaking the tie works on the following order of precedence:
# 1. First pair (default 0)
# 2. Second pair (default 0)
# 3. Compare all cards in reverse order because they are sorted.
# First pair and second pair will only be a non-zero value if the card
# type is either from the following:
# 21: Four of a kind
# 20: Full house
# 17: Three of a kind
# 16: Two pairs
# 15: One pair
if self._hand_type > other._hand_type:
return "Win"
elif self._hand_type < other._hand_type:
return "Loss"
elif self._first_pair == other._first_pair:
if self._second_pair == other._second_pair:
return self._compare_cards(other)
else:
return "Win" if self._second_pair > other._second_pair else "Loss"
return "Win" if self._first_pair > other._first_pair else "Loss"
# This function is not part of the problem, I did it just for fun
def hand_name(self) -> str:
name = PokerHand._HAND_NAME[self._hand_type - 14]
high = PokerHand._CARD_NAME[self._high_card]
pair1 = PokerHand._CARD_NAME[self._first_pair]
pair2 = PokerHand._CARD_NAME[self._second_pair]
if self._hand_type in [22, 19, 18]:
return name + f", {high}-high"
elif self._hand_type in [21, 17, 15]:
return name + f", {pair1}s"
elif self._hand_type in [20, 16]:
join = "over" if self._hand_type == 20 else "and"
return name + f", {pair1}s {join} {pair2}s"
elif self._hand_type == 23:
return name
else:
return name + f", {high}"
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]:
return "Win" if card_value > other._card_values[index] else "Loss"
return "Tie"
def _get_hand_type(self) -> int:
# Number representing the type of hand internally:
# 23: Royal flush
# 22: Straight flush
# 21: Four of a kind
# 20: Full house
# 19: Flush
# 18: Straight
# 17: Three of a kind
# 16: Two pairs
# 15: One pair
# 14: High card
if self._is_flush():
if self._is_five_high_straight() or self._is_straight():
return 23 if sum(self._card_values) == 60 else 22
return 19
elif self._is_five_high_straight() or self._is_straight():
return 18
return 14 + self._is_same_kind()
def _is_flush(self) -> bool:
return len(self._card_suit) == 1
def _is_five_high_straight(self) -> bool:
# If a card is a five high straight (low ace) change the location of
# ace from the start of the list to the end. Check whether the first
# element is ace or not. (Don't want to change again)
# Five high straight (low ace): AH 2H 3S 4C 5D
# Why use sorted here? One call to this function will mutate the list to
# [5, 4, 3, 2, 14] and so for subsequent calls (which will be rare) we
# need to compare the sorted version.
# Refer test_multiple_calls_five_high_straight in test_poker_hand.py
if sorted(self._card_values) == [2, 3, 4, 5, 14]:
if self._card_values[0] == 14:
# Remember, our list is sorted in reverse order
ace_card = self._card_values.pop(0)
self._card_values.append(ace_card)
return True
return False
def _is_straight(self) -> bool:
for i in range(4):
if self._card_values[i] - self._card_values[i + 1] != 1:
return False
return True
def _is_same_kind(self) -> int:
# Kind Values for internal use:
# 7: Four of a kind
# 6: Full house
# 3: Three of a kind
# 2: Two pairs
# 1: One pair
# 0: False
kind = val1 = val2 = 0
for i in range(4):
# Compare two cards at a time, if they are same increase 'kind',
# add the value of the card to val1, if it is repeating again we
# will add 2 to 'kind' as there are now 3 cards with same value.
# If we get card of different value than val1, we will do the same
# thing with val2
if self._card_values[i] == self._card_values[i + 1]:
if not val1:
val1 = self._card_values[i]
kind += 1
elif val1 == self._card_values[i]:
kind += 2
elif not val2:
val2 = self._card_values[i]
kind += 1
elif val2 == self._card_values[i]:
kind += 2
# For consistency in hand type (look at note in _get_hand_type function)
kind = kind + 2 if kind in [4, 5] else kind
# first meaning first pair to compare in 'compare_with'
first = max(val1, val2)
second = min(val1, val2)
# If it's full house (three count pair + two count pair), make sure
# first pair is three count and if not then switch them both.
if kind == 6 and self._card_values.count(first) != 3:
first, second = second, first
self._first_pair = first
self._second_pair = second
return kind
def _internal_state(self) -> tuple[list[int], set[str]]:
# Internal representation of hand as a list of card values and
# a set of card suit
trans: dict = {"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"}
new_hand = self._hand.translate(str.maketrans(trans)).split()
card_values = [int(card[:-1]) for card in new_hand]
card_suit = {card[-1] for card in new_hand}
return sorted(card_values, reverse=True), card_suit
def __repr__(self):
return f'{self.__class__}("{self._hand}")'
def __str__(self):
return self._hand
# Rich comparison operators (used in list.sort() and sorted() builtin functions)
# Note that this is not part of the problem but another extra feature where
# if you have a list of PokerHand objects, you can sort them just through
# the builtin functions.
def __eq__(self, other):
if isinstance(other, PokerHand):
return self.compare_with(other) == "Tie"
return NotImplemented
def __lt__(self, other):
if isinstance(other, PokerHand):
return self.compare_with(other) == "Loss"
return NotImplemented
def __le__(self, other):
if isinstance(other, PokerHand):
return self < other or self == other
return NotImplemented
def __gt__(self, other):
if isinstance(other, PokerHand):
return not self < other and self != other
return NotImplemented
def __ge__(self, other):
if isinstance(other, PokerHand):
return not self < other
return NotImplemented
def __hash__(self):
return object.__hash__(self)
def solution() -> int:
# Solution for problem number 54 from Project Euler
# Input from poker_hands.txt file
answer = 0
script_dir = os.path.abspath(os.path.dirname(__file__))
poker_hands = os.path.join(script_dir, "poker_hands.txt")
with open(poker_hands) as file_hand:
for line in file_hand:
player_hand = line[:14].strip()
opponent_hand = line[15:].strip()
player, opponent = PokerHand(player_hand), PokerHand(opponent_hand)
output = player.compare_with(opponent)
if output == "Win":
answer += 1
return answer
if __name__ == "__main__":
solution() | --- +++ @@ -1,3 +1,45 @@+"""
+Problem: https://projecteuler.net/problem=54
+
+In the card game poker, a hand consists of five cards and are ranked,
+from lowest to highest, in the following way:
+
+High Card: Highest value card.
+One Pair: Two cards of the same value.
+Two Pairs: Two different pairs.
+Three of a Kind: Three cards of the same value.
+Straight: All cards are consecutive values.
+Flush: All cards of the same suit.
+Full House: Three of a kind and a pair.
+Four of a Kind: Four cards of the same value.
+Straight Flush: All cards are consecutive values of same suit.
+Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
+
+The cards are valued in the order:
+2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
+
+If two players have the same ranked hands then the rank made up of the highest
+value wins; for example, a pair of eights beats a pair of fives.
+But if two ranks tie, for example, both players have a pair of queens, then highest
+cards in each hand are compared; if the highest cards tie then the next highest
+cards are compared, and so on.
+
+The file, poker.txt, contains one-thousand random hands dealt to two players.
+Each line of the file contains ten cards (separated by a single space): the
+first five are Player 1's cards and the last five are Player 2's cards.
+You can assume that all hands are valid (no invalid characters or repeated cards),
+each player's hand is in no specific order, and in each hand there is a clear winner.
+
+How many hands does Player 1 win?
+
+Resources used:
+https://en.wikipedia.org/wiki/Texas_hold_%27em
+https://en.wikipedia.org/wiki/List_of_poker_hands
+
+Similar problem on codewars:
+https://www.codewars.com/kata/ranking-poker-hands
+https://www.codewars.com/kata/sortable-poker-hands
+"""
from __future__ import annotations
@@ -5,6 +47,29 @@
class PokerHand:
+ """Create an object representing a Poker Hand based on an input of a
+ string which represents the best 5-card combination from the player's hand
+ and board cards.
+
+ Attributes: (read-only)
+ hand: a string representing the hand consisting of five cards
+
+ Methods:
+ compare_with(opponent): takes in player's hand (self) and
+ opponent's hand (opponent) and compares both hands according to
+ the rules of Texas Hold'em.
+ Returns one of 3 strings (Win, Loss, Tie) based on whether
+ player's hand is better than the opponent's hand.
+
+ hand_name(): Returns a string made up of two parts: hand name
+ and high card.
+
+ Supported operators:
+ Rich comparison operators: <, >, <=, >=, ==, !=
+
+ Supported built-in methods and functions:
+ list.sort(), sorted()
+ """
_HAND_NAME = (
"High card",
@@ -38,6 +103,22 @@ )
def __init__(self, hand: str) -> None:
+ """
+ Initialize hand.
+ Hand should of type str and should contain only five cards each
+ separated by a space.
+
+ The cards should be of the following format:
+ [card value][card suit]
+
+ The first character is the value of the card:
+ 2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)
+
+ The second character represents the suit:
+ S(pades), H(earts), D(iamonds), C(lubs)
+
+ For example: "6S 4C KC AS TH"
+ """
if not isinstance(hand, str):
msg = f"Hand should be of type 'str': {hand!r}"
raise TypeError(msg)
@@ -54,9 +135,31 @@
@property
def hand(self):
+ """Returns the self hand"""
return self._hand
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
+ Texas Hold'em.
+
+ Here are some examples:
+ >>> player = PokerHand("2H 3H 4H 5H 6H") # Stright flush
+ >>> opponent = PokerHand("KS AS TS QS JS") # Royal flush
+ >>> player.compare_with(opponent)
+ 'Loss'
+
+ >>> player = PokerHand("2S AH 2H AS AC") # Full house
+ >>> opponent = PokerHand("2H 3H 5H 6H 7H") # Flush
+ >>> player.compare_with(opponent)
+ 'Win'
+
+ >>> player = PokerHand("2S AH 4H 5S 6C") # High card
+ >>> opponent = PokerHand("AD 4C 5H 6H 2C") # High card
+ >>> player.compare_with(opponent)
+ 'Tie'
+ """
# Breaking the tie works on the following order of precedence:
# 1. First pair (default 0)
# 2. Second pair (default 0)
@@ -82,6 +185,28 @@
# This function is not part of the problem, I did it just for fun
def hand_name(self) -> str:
+ """
+ Return the name of the hand in the following format:
+ 'hand name, high card'
+
+ Here are some examples:
+ >>> PokerHand("KS AS TS QS JS").hand_name()
+ 'Royal flush'
+
+ >>> PokerHand("2D 6D 3D 4D 5D").hand_name()
+ 'Straight flush, Six-high'
+
+ >>> PokerHand("JC 6H JS JD JH").hand_name()
+ 'Four of a kind, Jacks'
+
+ >>> PokerHand("3D 2H 3H 2C 2D").hand_name()
+ 'Full house, Twos over Threes'
+
+ >>> PokerHand("2H 4D 3C AS 5S").hand_name() # Low ace
+ 'Straight, Five-high'
+
+ Source: https://en.wikipedia.org/wiki/List_of_poker_hands
+ """
name = PokerHand._HAND_NAME[self._hand_type - 14]
high = PokerHand._CARD_NAME[self._high_card]
pair1 = PokerHand._CARD_NAME[self._first_pair]
@@ -256,4 +381,4 @@
if __name__ == "__main__":
- solution()+ solution()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_054/sol1.py |
Add docstrings for better understanding |
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)
)
# Tests
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,31 @@+"""
+Project Euler Problem 56: https://projecteuler.net/problem=56
+
+A googol (10^100) is a massive number: one followed by one-hundred zeros;
+100^100 is almost unimaginably large: one followed by two-hundred zeros.
+Despite their size, the sum of the digits in each number is only 1.
+
+Considering natural numbers of the form, ab, where a, b < 100,
+what is the maximum digital sum?
+"""
def solution(a: int = 100, b: int = 100) -> int:
+ """
+ Considering natural numbers of the form, a**b, where a, b < 100,
+ what is the maximum digital sum?
+ :param a:
+ :param b:
+ :return:
+ >>> solution(10,10)
+ 45
+
+ >>> solution(100,100)
+ 972
+
+ >>> solution(100,200)
+ 1872
+ """
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
# BASE raised to the POWER
@@ -13,4 +38,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_056/sol1.py |
Create docstrings for reusable components |
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
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}
COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None:
decoded: str = ""
keychar: int
cipherchar: int
decodedchar: int
for keychar, cipherchar in zip(cycle(key), ciphertext):
decodedchar = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(decodedchar)
return decoded
def filter_valid_chars(ciphertext: list[int]) -> list[str]:
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
if encoded is not None:
possibles.append(encoded)
return possibles
def filter_common_word(possibles: list[str], common_word: str) -> list[str]:
return [possible for possible in possibles if common_word in possible.lower()]
def solution(filename: str = "p059_cipher.txt") -> int:
ciphertext: list[int]
possibles: list[str]
common_word: str
decoded_text: str
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
ciphertext = [int(number) for number in data.strip().split(",")]
possibles = filter_valid_chars(ciphertext)
for common_word in COMMON_WORDS:
possibles = filter_common_word(possibles, common_word)
if len(possibles) == 1:
break
decoded_text = possibles[0]
return sum(ord(char) for char in decoded_text)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,3 +1,30 @@+"""
+Each character on a computer is assigned a unique code and the preferred standard is
+ASCII (American Standard Code for Information Interchange).
+For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
+
+A modern encryption method is to take a text file, convert the bytes to ASCII, then
+XOR each byte with a given value, taken from a secret key. The advantage with the
+XOR function is that using the same encryption key on the cipher text, restores
+the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
+
+For unbreakable encryption, the key is the same length as the plain text message, and
+the key is made up of random bytes. The user would keep the encrypted message and the
+encryption key in different locations, and without both "halves", it is impossible to
+decrypt the message.
+
+Unfortunately, this method is impractical for most users, so the modified method is
+to use a password as a key. If the password is shorter than the message, which is
+likely, the key is repeated cyclically throughout the message. The balance for this
+method is using a sufficiently long password key for security, but short enough to
+be memorable.
+
+Your task has been made easy, as the encryption key consists of three lower case
+characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a
+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
@@ -15,6 +42,16 @@
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,
+ a digit, punctuation or whitespace, then we know the key is incorrect, so return
+ None.
+ >>> try_key([0, 17, 20, 4, 27], (104, 116, 120))
+ 'hello'
+ >>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None
+ True
+ """
decoded: str = ""
keychar: int
cipherchar: int
@@ -30,6 +67,16 @@
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.
+ >>> from itertools import cycle
+ >>> text = "The enemy's gate is down"
+ >>> key = "end"
+ >>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)]
+ >>> text in filter_valid_chars(encoded)
+ True
+ """
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
@@ -39,10 +86,26 @@
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
+ containing common_word will be returned.
+ >>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am')
+ ['I am here']
+ >>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am')
+ ['athla amf', 'I am here']
+ """
return [possible for possible in possibles if common_word in possible.lower()]
def solution(filename: str = "p059_cipher.txt") -> int:
+ """
+ Test the ciphertext against all possible 3-character keys, then narrow down the
+ possibilities by filtering using common words until there's only one possible
+ decoded message.
+ >>> solution("test_cipher.txt")
+ 3000
+ """
ciphertext: list[int]
possibles: list[str]
common_word: str
@@ -62,4 +125,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_059/sol1.py |
Create docstrings for reusable components |
from functools import lru_cache
def unique_prime_factors(n: int) -> set:
i = 2
factors = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.add(i)
if n > 1:
factors.add(n)
return factors
@lru_cache
def upf_len(num: int) -> int:
return len(unique_prime_factors(num))
def equality(iterable: list) -> bool:
return len(set(iterable)) in (0, 1)
def run(n: int) -> list[int]:
# Incrementor variable for our group list comprehension.
# This is the first number in each list of values
# to test.
base = 2
while True:
# Increment each value of a generated range
group = [base + i for i in range(n)]
# Run elements through the unique_prime_factors function
# Append our target number to the end.
checker = [upf_len(x) for x in group]
checker.append(n)
# If all numbers in the list are equal, return the group variable.
if equality(checker):
return group
# Increment our base variable by 1
base += 1
def solution(n: int = 4) -> int | None:
results = run(n)
return results[0] if len(results) else None
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,38 @@+"""
+Combinatoric selections
+
+Problem 47
+
+The first two consecutive numbers to have two distinct prime factors are:
+
+14 = 2 x 7
+15 = 3 x 5
+
+The first three consecutive numbers to have three distinct prime factors are:
+
+644 = 2² x 7 x 23
+645 = 3 x 5 x 43
+646 = 2 x 17 x 19.
+
+Find the first four consecutive integers to have four distinct prime factors each.
+What is the first of these numbers?
+"""
from functools import lru_cache
def unique_prime_factors(n: int) -> set:
+ """
+ Find unique prime factors of an integer.
+ Tests include sorting because only the set matters,
+ not the order in which it is produced.
+ >>> sorted(set(unique_prime_factors(14)))
+ [2, 7]
+ >>> sorted(set(unique_prime_factors(644)))
+ [2, 7, 23]
+ >>> sorted(set(unique_prime_factors(646)))
+ [2, 17, 19]
+ """
i = 2
factors = set()
while i * i <= n:
@@ -18,14 +48,33 @@
@lru_cache
def upf_len(num: int) -> int:
+ """
+ Memoize upf() length results for a given value.
+ >>> upf_len(14)
+ 2
+ """
return len(unique_prime_factors(num))
def equality(iterable: list) -> bool:
+ """
+ Check the equality of ALL elements in an iterable
+ >>> equality([1, 2, 3, 4])
+ False
+ >>> equality([2, 2, 2, 2])
+ True
+ >>> equality([1, 2, 3, 2, 1])
+ False
+ """
return len(set(iterable)) in (0, 1)
def run(n: int) -> list[int]:
+ """
+ Runs core process to find problem solution.
+ >>> run(3)
+ [644, 645, 646]
+ """
# Incrementor variable for our group list comprehension.
# This is the first number in each list of values
@@ -50,9 +99,14 @@
def solution(n: int = 4) -> int | None:
+ """Return the first value of the first four consecutive integers to have four
+ distinct prime factors each.
+ >>> solution()
+ 134043
+ """
results = run(n)
return results[0] if len(results) else None
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_047/sol1.py |
Add professional docstrings to my codebase |
"""
The maximum base can be 9 because all n-digit numbers < 10^n.
Now 9**23 has 22 digits so the maximum power can be 22.
Using these conclusions, we will calculate the result.
"""
def solution(max_base: int = 10, max_power: int = 22) -> int:
bases = range(1, max_base)
powers = range(1, max_power)
return sum(
1 for power in powers for base in bases if len(str(base**power)) == power
)
if __name__ == "__main__":
print(f"{solution(10, 22) = }") | --- +++ @@ -1,18 +1,34 @@-
-"""
-The maximum base can be 9 because all n-digit numbers < 10^n.
-Now 9**23 has 22 digits so the maximum power can be 22.
-Using these conclusions, we will calculate the result.
-"""
-
-
-def solution(max_base: int = 10, max_power: int = 22) -> int:
- bases = range(1, max_base)
- powers = range(1, max_power)
- return sum(
- 1 for power in powers for base in bases if len(str(base**power)) == power
- )
-
-
-if __name__ == "__main__":
- print(f"{solution(10, 22) = }")+"""
+The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number,
+134217728=89, is a ninth power.
+How many n-digit positive integers exist which are also an nth power?
+"""
+
+"""
+The maximum base can be 9 because all n-digit numbers < 10^n.
+Now 9**23 has 22 digits so the maximum power can be 22.
+Using these conclusions, we will calculate the result.
+"""
+
+
+def solution(max_base: int = 10, max_power: int = 22) -> int:
+ """
+ Returns the count of all n-digit numbers which are nth power
+ >>> solution(10, 22)
+ 49
+ >>> solution(0, 0)
+ 0
+ >>> solution(1, 1)
+ 0
+ >>> solution(-1, -1)
+ 0
+ """
+ bases = range(1, max_base)
+ powers = range(1, max_power)
+ return sum(
+ 1 for power in powers for base in bases if len(str(base**power)) == power
+ )
+
+
+if __name__ == "__main__":
+ print(f"{solution(10, 22) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_063/sol1.py |
Generate docstrings for this script |
import os
def solution():
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = []
for line in triangle:
numbers_from_line = []
for number in line.strip().split(" "):
numbers_from_line.append(int(number))
a.append(numbers_from_line)
for i in range(1, len(a)):
for j in range(len(a[i])):
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number2 = a[i - 1][j - 1] if j > 0 else 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,28 @@+"""
+Problem Statement:
+By starting at the top of the triangle below and moving to adjacent numbers on
+the row below, the maximum total from top to bottom is 23.
+3
+7 4
+2 4 6
+8 5 9 3
+That is, 3 + 7 + 4 + 9 = 23.
+Find the maximum total from top to bottom in triangle.txt (right click and
+'Save Link/Target As...'), a 15K text file containing a triangle with
+one-hundred rows.
+"""
import os
def solution():
+ """
+ Finds the maximum total in a triangle as described by the problem statement
+ above.
+
+ >>> solution()
+ 7273
+ """
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
@@ -25,4 +45,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_067/sol1.py |
Create docstrings for reusable components |
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
numerator = 0.0
denominator = 1.0
root = int(sqrt(n))
integer_part = root
period = 0
while integer_part != 2 * root:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((root + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}") | --- +++ @@ -1,8 +1,36 @@+"""
+Project Euler Problem 64: https://projecteuler.net/problem=64
+
+All square roots are periodic when written as continued fractions.
+For example, let us consider sqrt(23).
+It can be seen that the sequence is repeating.
+For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
+to indicate that the block (1,3,1,8) repeats indefinitely.
+Exactly four continued fractions, for N<=13, have an odd period.
+How many continued fractions for N<=10000 have an odd period?
+
+References:
+- https://en.wikipedia.org/wiki/Continued_fraction
+"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
+ """
+ Returns the continued fraction period of a number n.
+
+ >>> continuous_fraction_period(2)
+ 1
+ >>> continuous_fraction_period(5)
+ 1
+ >>> continuous_fraction_period(7)
+ 4
+ >>> continuous_fraction_period(11)
+ 2
+ >>> continuous_fraction_period(13)
+ 5
+ """
numerator = 0.0
denominator = 1.0
root = int(sqrt(n))
@@ -17,6 +45,25 @@
def solution(n: int = 10000) -> int:
+ """
+ Returns the count of numbers <= 10000 with odd periods.
+ This function calls continuous_fraction_period for numbers which are
+ not perfect squares.
+ This is checked in if sr - floor(sr) != 0 statement.
+ If an odd period is returned by continuous_fraction_period,
+ count_odd_periods is increased by 1.
+
+ >>> solution(2)
+ 1
+ >>> solution(5)
+ 2
+ >>> solution(7)
+ 2
+ >>> solution(11)
+ 3
+ >>> solution(13)
+ 4
+ """
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
@@ -26,4 +73,4 @@
if __name__ == "__main__":
- print(f"{solution(int(input().strip()))}")+ print(f"{solution(int(input().strip()))}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_064/sol1.py |
Generate documentation strings for clarity |
from itertools import permutations
def solution(gon_side: int = 5) -> int:
if gon_side < 3 or gon_side > 5:
raise ValueError("gon_side must be in the range [3, 5]")
# Since it's 16, we know 10 is on the outer ring
# Put the big numbers at the end so that they are never the first number
small_numbers = list(range(gon_side + 1, 0, -1))
big_numbers = list(range(gon_side + 2, gon_side * 2 + 1))
for perm in permutations(small_numbers + big_numbers):
numbers = generate_gon_ring(gon_side, list(perm))
if is_magic_gon(numbers):
return int("".join(str(n) for n in numbers))
msg = f"Magic {gon_side}-gon ring is impossible"
raise ValueError(msg)
def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]:
result = [0] * (gon_side * 3)
result[0:3] = perm[0:3]
perm.append(perm[1])
magic_number = 1 if gon_side < 5 else 2
for i in range(1, len(perm) // 3 + magic_number):
result[3 * i] = perm[2 * i + 1]
result[3 * i + 1] = result[3 * i - 1]
result[3 * i + 2] = perm[2 * i + 2]
return result
def is_magic_gon(numbers: list[int]) -> bool:
if len(numbers) % 3 != 0:
raise ValueError("a gon ring should have a length that is a multiple of 3")
if min(numbers[::3]) != numbers[0]:
return False
total = sum(numbers[:3])
return all(sum(numbers[i : i + 3]) == total for i in range(3, len(numbers), 3))
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,8 +1,65 @@+"""
+Project Euler Problem 68: https://projecteuler.net/problem=68
+
+Magic 5-gon ring
+
+Problem Statement:
+Consider the following "magic" 3-gon ring,
+filled with the numbers 1 to 6, and each line adding to nine.
+
+ 4
+ \
+ 3
+ / \
+ 1 - 2 - 6
+ /
+ 5
+
+Working clockwise, and starting from the group of three
+with the numerically lowest external node (4,3,2 in this example),
+each solution can be described uniquely.
+For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.
+
+It is possible to complete the ring with four different totals: 9, 10, 11, and 12.
+There are eight solutions in total.
+Total Solution Set
+9 4,2,3; 5,3,1; 6,1,2
+9 4,3,2; 6,2,1; 5,1,3
+10 2,3,5; 4,5,1; 6,1,3
+10 2,5,3; 6,3,1; 4,1,5
+11 1,4,6; 3,6,2; 5,2,4
+11 1,6,4; 5,4,2; 3,2,6
+12 1,5,6; 2,6,4; 3,4,5
+12 1,6,5; 3,5,4; 2,4,6
+
+By concatenating each group it is possible to form 9-digit strings;
+the maximum string for a 3-gon ring is 432621513.
+
+Using the numbers 1 to 10, and depending on arrangements,
+it is possible to form 16- and 17-digit strings.
+What is the maximum 16-digit string for a "magic" 5-gon ring?
+"""
from itertools import permutations
def solution(gon_side: int = 5) -> int:
+ """
+ Find the maximum number for a "magic" gon_side-gon ring
+
+ The gon_side parameter should be in the range [3, 5],
+ other side numbers aren't tested
+
+ >>> solution(3)
+ 432621513
+ >>> solution(4)
+ 426561813732
+ >>> solution()
+ 6531031914842725
+ >>> solution(6)
+ Traceback (most recent call last):
+ ValueError: gon_side must be in the range [3, 5]
+ """
if gon_side < 3 or gon_side > 5:
raise ValueError("gon_side must be in the range [3, 5]")
@@ -21,6 +78,15 @@
def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]:
+ """
+ Generate a gon_side-gon ring from a permutation state
+ The permutation state is the ring, but every duplicate is removed
+
+ >>> generate_gon_ring(3, [4, 2, 3, 5, 1, 6])
+ [4, 2, 3, 5, 3, 1, 6, 1, 2]
+ >>> generate_gon_ring(5, [6, 5, 4, 3, 2, 1, 7, 8, 9, 10])
+ [6, 5, 4, 3, 4, 2, 1, 2, 7, 8, 7, 9, 10, 9, 5]
+ """
result = [0] * (gon_side * 3)
result[0:3] = perm[0:3]
perm.append(perm[1])
@@ -36,6 +102,23 @@
def is_magic_gon(numbers: list[int]) -> bool:
+ """
+ Check if the solution set is a magic n-gon ring
+ Check that the first number is the smallest number on the outer ring
+ Take a list, and check if the sum of each 3 numbers chunk is equal to the same total
+
+ >>> is_magic_gon([4, 2, 3, 5, 3, 1, 6, 1, 2])
+ True
+ >>> is_magic_gon([4, 3, 2, 6, 2, 1, 5, 1, 3])
+ True
+ >>> is_magic_gon([2, 3, 5, 4, 5, 1, 6, 1, 3])
+ True
+ >>> is_magic_gon([1, 2, 3, 4, 5, 6, 7, 8, 9])
+ False
+ >>> is_magic_gon([1])
+ Traceback (most recent call last):
+ ValueError: a gon ring should have a length that is a multiple of 3
+ """
if len(numbers) % 3 != 0:
raise ValueError("a gon ring should have a length that is a multiple of 3")
@@ -48,4 +131,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_068/sol1.py |
Add structured docstrings to improve clarity |
def solution(n: int = 10**6) -> int:
if n <= 0:
raise ValueError("Please enter an integer greater than 0")
phi = list(range(n + 1))
for number in range(2, n + 1):
if phi[number] == number:
phi[number] -= 1
for multiple in range(number * 2, n + 1, number):
phi[multiple] = (phi[multiple] // number) * (number - 1)
answer = 1
for number in range(1, n + 1):
if (answer / phi[answer]) < (number / phi[number]):
answer = number
return answer
if __name__ == "__main__":
print(solution()) | --- +++ @@ -1,6 +1,48 @@+"""
+Totient maximum
+Problem 69: https://projecteuler.net/problem=69
+
+Euler's Totient function, φ(n) [sometimes called the phi function],
+is used to determine the number of numbers less than n which are relatively prime to n.
+For example, as 1, 2, 4, 5, 7, and 8,
+are all less than nine and relatively prime to nine, φ(9)=6.
+
+n Relatively Prime φ(n) n/φ(n)
+2 1 1 2
+3 1,2 2 1.5
+4 1,3 2 2
+5 1,2,3,4 4 1.25
+6 1,5 2 3
+7 1,2,3,4,5,6 6 1.1666...
+8 1,3,5,7 4 2
+9 1,2,4,5,7,8 6 1.5
+10 1,3,7,9 4 2.5
+
+It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10.
+
+Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
+"""
def solution(n: int = 10**6) -> int:
+ """
+ Returns solution to problem.
+ Algorithm:
+ 1. Precompute φ(k) for all natural k, k <= n using product formula (wikilink below)
+ https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula
+
+ 2. Find k/φ(k) for all k ≤ n and return the k that attains maximum
+
+ >>> solution(10)
+ 6
+
+ >>> solution(100)
+ 30
+
+ >>> solution(9973)
+ 2310
+
+ """
if n <= 0:
raise ValueError("Please enter an integer greater than 0")
@@ -21,4 +63,4 @@
if __name__ == "__main__":
- print(solution())+ print(solution())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_069/sol1.py |
Write beginner-friendly docstrings |
def sum_digits(num: int) -> int:
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
return digit_sum
def solution(max_n: int = 100) -> int:
pre_numerator = 1
cur_numerator = 2
for i in range(2, max_n + 1):
temp = pre_numerator
e_cont = 2 * i // 3 if i % 3 == 0 else 1
pre_numerator = cur_numerator
cur_numerator = e_cont * pre_numerator + temp
return sum_digits(cur_numerator)
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,6 +1,69 @@+"""
+Project Euler Problem 65: https://projecteuler.net/problem=65
+
+The square root of 2 can be written as an infinite continued fraction.
+
+sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...))))
+
+The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2)
+indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) =
+[4;(1,3,1,8)].
+
+It turns out that the sequence of partial values of continued
+fractions for square roots provide the best rational approximations.
+Let us consider the convergents for sqrt(2).
+
+1 + 1 / 2 = 3/2
+1 + 1 / (2 + 1 / 2) = 7/5
+1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12
+1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29
+
+Hence the sequence of the first ten convergents for sqrt(2) are:
+1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...
+
+What is most surprising is that the important mathematical constant,
+e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...].
+
+The first ten terms in the sequence of convergents for e are:
+2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
+
+The sum of digits in the numerator of the 10th convergent is
+1 + 4 + 5 + 7 = 17.
+
+Find the sum of the digits in the numerator of the 100th convergent
+of the continued fraction for e.
+
+-----
+
+The solution mostly comes down to finding an equation that will generate
+the numerator of the continued fraction. For the i-th numerator, the
+pattern is:
+
+n_i = m_i * n_(i-1) + n_(i-2)
+
+for m_i = the i-th index of the continued fraction representation of e,
+n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation.
+
+For example:
+n_9 = 6 * 193 + 106 = 1264
+1 + 2 + 6 + 4 = 13
+
+n_10 = 1 * 193 + 1264 = 1457
+1 + 4 + 5 + 7 = 17
+"""
def sum_digits(num: int) -> int:
+ """
+ Returns the sum of every digit in num.
+
+ >>> sum_digits(1)
+ 1
+ >>> sum_digits(12345)
+ 15
+ >>> sum_digits(999001)
+ 28
+ """
digit_sum = 0
while num > 0:
digit_sum += num % 10
@@ -9,6 +72,17 @@
def solution(max_n: int = 100) -> int:
+ """
+ Returns the sum of the digits in the numerator of the max-th convergent of
+ the continued fraction for e.
+
+ >>> solution(9)
+ 13
+ >>> solution(10)
+ 17
+ >>> solution(50)
+ 91
+ """
pre_numerator = 1
cur_numerator = 2
@@ -22,4 +96,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_065/sol1.py |
Generate docstrings for script automation |
from __future__ import annotations
import numpy as np
def get_totients(max_one: int) -> list[int]:
totients = np.arange(max_one)
for i in range(2, max_one):
if totients[i] == i:
x = np.arange(i, max_one, i) # array of indexes to select
totients[x] -= totients[x] // i
return totients.tolist()
def has_same_digits(num1: int, num2: int) -> bool:
return sorted(str(num1)) == sorted(str(num2))
def solution(max_n: int = 10000000) -> int:
min_numerator = 1 # i
min_denominator = 0 # φ(i)
totients = get_totients(max_n + 1)
for i in range(2, max_n + 1):
t = totients[i]
if i * min_denominator < min_numerator * t and has_same_digits(i, t):
min_numerator = i
min_denominator = t
return min_numerator
if __name__ == "__main__":
print(f"{solution() = }") | --- +++ @@ -1,3 +1,33 @@+"""
+Project Euler Problem 70: https://projecteuler.net/problem=70
+
+Euler's Totient function, φ(n) [sometimes called the phi function], is used to
+determine the number of positive numbers less than or equal to n which are
+relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than
+nine and relatively prime to nine, φ(9)=6.
+
+The number 1 is considered to be relatively prime to every positive number, so
+φ(1)=1.
+
+Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation
+of 79180.
+
+Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and
+the ratio n/φ(n) produces a minimum.
+
+-----
+
+This is essentially brute force. Calculate all totients up to 10^7 and
+find the minimum ratio of n/φ(n) that way. To minimize the ratio, we want
+to minimize n and maximize φ(n) as much as possible, so we can store the
+minimum fraction's numerator and denominator and calculate new fractions
+with each totient to compare against. To avoid dividing by zero, I opt to
+use cross multiplication.
+
+References:
+Finding totients
+https://en.wikipedia.org/wiki/Euler's_totient_function#Euler's_product_formula
+"""
from __future__ import annotations
@@ -5,6 +35,16 @@
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.
+
+ >>> get_totients(5)
+ [0, 1, 1, 2, 2]
+
+ >>> get_totients(10)
+ [0, 1, 1, 2, 2, 4, 2, 6, 4, 6]
+ """
totients = np.arange(max_one)
for i in range(2, max_one):
@@ -16,10 +56,32 @@
def has_same_digits(num1: int, num2: int) -> bool:
+ """
+ Return True if num1 and num2 have the same frequency of every digit, False
+ otherwise.
+
+ >>> has_same_digits(123456789, 987654321)
+ True
+
+ >>> has_same_digits(123, 23)
+ False
+
+ >>> has_same_digits(1234566, 123456)
+ False
+ """
return sorted(str(num1)) == sorted(str(num2))
def solution(max_n: int = 10000000) -> int:
+ """
+ Finds the value of n from 1 to max such that n/φ(n) produces a minimum.
+
+ >>> solution(100)
+ 21
+
+ >>> solution(10000)
+ 4435
+ """
min_numerator = 1 # i
min_denominator = 0 # φ(i)
@@ -36,4 +98,4 @@
if __name__ == "__main__":
- print(f"{solution() = }")+ print(f"{solution() = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_070/sol1.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.