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... | --- +++ @@ -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... | 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... | 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 _... | --- +++ @@ -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... | 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:
... | --- +++ @@ -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
+"""
... | 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-... | --- +++ @@ -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-... | 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... | --- +++ @@ -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
+"""
... | 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:... | --- +++ @@ -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
+"""
... | 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 divisibl... | --- +++ @@ -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... | 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.... | --- +++ @@ -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... | 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)
... | --- +++ @@ -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 t... | 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... | 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
+
+Hen... | 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 _... | --- +++ @@ -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:... | 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... | --- +++ @@ -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
+"""
... | 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
+
+Hen... | 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
+
+Hen... | 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 ... | --- +++ @@ -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-... | 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
testm... | --- +++ @@ -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
+
+Ot... | 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 num... | --- +++ @@ -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
+"""
... | 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 ... | --- +++ @@ -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 ... | 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"
"62229893423... | --- +++ @@ -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
+ 9698352031277450632623957... | 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... | --- +++ @@ -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
+"""
... | 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)
... | --- +++ @@ -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):... | 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... | --- +++ @@ -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: Mutab... | 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"{so... | --- +++ @@ -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... | 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 * ... | --- +++ @@ -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... | 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,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 f... | 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... | --- +++ @@ -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... | 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,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 f... | 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... | --- +++ @@ -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 i... | 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 i... | --- +++ @@ -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... | 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... | 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 = ... | --- +++ @@ -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.or... | 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 n... | --- +++ @@ -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 coll... | 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 ... | 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_SEQ... | --- +++ @@ -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 ti... | 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 n... | --- +++ @@ -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:
+
+ ... | 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 =... | 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:
... | --- +++ @@ -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 factor... | 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 ^ ", po... | --- +++ @@ -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.
+ >>... | 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 =... | --- +++ @@ -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... | 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.
+
+ ... | 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)):
... | --- +++ @@ -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
+1... | 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... | 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_di... | --- +++ @@ -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... | 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... | --- +++ @@ -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, ... | 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 inc... | --- +++ @@ -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... | 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... | 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(
... | --- +++ @@ -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 d... | 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:
... | --- +++ @@ -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 di... | 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:
... | --- +++ @@ -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 p... | 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... | 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:
+
+ 0... | 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 += ... | --- +++ @@ -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 p... | 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... | --- +++ @@ -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
... | 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(inpu... | --- +++ @@ -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
... | 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
... | --- +++ @@ -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
... | 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... | --- +++ @@ -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(numb... | 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... | --- +++ @@ -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 ... | 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_divide... | --- +++ @@ -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.(... | 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 ... | --- +++ @@ -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 t... | 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_p... | --- +++ @@ -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 i... | 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... | --- +++ @@ -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 ... | 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... | --- +++ @@ -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 + 1... | 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]
retu... | --- +++ @@ -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 +... | 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)
... | --- +++ @@ -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, limi... | 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... | --- +++ @@ -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: in... | 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_... | --- +++ @@ -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, 3... | 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
... | --- +++ @@ -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... | 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:
... | --- +++ @@ -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
- ... | 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... | --- +++ @@ -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, a... | 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:
com... | --- +++ @@ -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
+ ... | 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 candi... | --- +++ @@ -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 pr... | 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__ == "... | --- +++ @@ -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 1... | 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):
hypo... | --- +++ @@ -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, ... | 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 = hexagon... | --- +++ @@ -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(nu... | 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)... | --- +++ @@ -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):
- fo... | 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
... | --- +++ @@ -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 sequen... | 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 ... | --- +++ @@ -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... | 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
... | --- +++ @@ -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... | 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
... | --- +++ @@ -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 longes... | 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[in... | --- +++ @@ -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 dig... | 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__... | --- +++ @@ -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, ... | 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:
... | --- +++ @@ -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
-... | 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
... | --- +++ @@ -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 t... | 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__ == ... | --- +++ @@ -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():
+ ... | 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... | --- +++ @@ -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 2... | 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.
+
+ >>> ... | 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.app... | --- +++ @@ -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 =... | 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",
)
... | --- +++ @@ -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: ... | 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__":
... | --- +++ @@ -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.
+
+Consi... | 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] =... | --- +++ @@ -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 byte... | 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) -> ... | --- +++ @@ -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 t... | 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... | --- +++ @@ -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)
- pow... | 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(... | --- +++ @@ -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
+... | 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) ... | --- +++ @@ -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 indi... | 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... | --- +++ @@ -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, an... | 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):
... | --- +++ @@ -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 an... | 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 i... | --- +++ @@ -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 r... | 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
r... | --- +++ @@ -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 ... | 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.