From 897f1d0fb4c4f78dd8a7e82820e843f7f9f38738 Mon Sep 17 00:00:00 2001 From: PatOnTheBack <51241310+PatOnTheBack@users.noreply.github.com> Date: Wed, 10 Jul 2019 16:09:24 -0400 Subject: [PATCH] Improved Formatting and Style of Math Algos (#960) * Improved Formatting and Style I improved formatting and style to make PyLama happier. Linters used: - mccabe - pep257 - pydocstyle - pep8 - pycodestyle - pyflakes - pylint - isort * Create volume.py This script calculates the volumes of various shapes. * Delete lucasSeries.py * Revert "Delete lucasSeries.py" This reverts commit 64c19f7a6c8b74e15bed07f0f0337598a001ceb4. * Update lucasSeries.py --- maths/Binary_Exponentiation.py | 30 ++++---- maths/Find_Min.py | 21 +++--- maths/Prime_Check.py | 49 +++++++------ maths/abs.py | 13 ++-- maths/extended_euclidean_algorithm.py | 53 +++++++++----- maths/fermat_little_theorem.py | 6 +- maths/greater_common_divisor.py | 18 +++-- maths/modular_exponential.py | 31 ++++---- maths/segmented_sieve.py | 43 ++++++----- maths/sieve_of_eratosthenes.py | 31 ++++---- maths/simpson_rule.py | 58 +++++++-------- maths/trapezoidal_rule.py | 24 +++---- maths/volume.py | 100 ++++++++++++++++++++++++++ 13 files changed, 317 insertions(+), 160 deletions(-) create mode 100644 maths/volume.py diff --git a/maths/Binary_Exponentiation.py b/maths/Binary_Exponentiation.py index 2411cd58a..cf789afc6 100644 --- a/maths/Binary_Exponentiation.py +++ b/maths/Binary_Exponentiation.py @@ -1,25 +1,27 @@ -#Author : Junth Basnet -#Time Complexity : O(logn) +"""Binary Exponentiation.""" + +# Author : Junth Basnet +# Time Complexity : O(logn) + def binary_exponentiation(a, n): - + if (n == 0): return 1 - + elif (n % 2 == 1): return binary_exponentiation(a, n - 1) * a - + else: b = binary_exponentiation(a, n / 2) return b * b - -try: - base = int(input('Enter Base : ')) - power = int(input("Enter Power : ")) -except ValueError: - print ("Invalid literal for integer") -result = binary_exponentiation(base, power) -print("{}^({}) : {}".format(base, power, result)) - +try: + BASE = int(input('Enter Base : ')) + POWER = int(input("Enter Power : ")) +except ValueError: + print("Invalid literal for integer") + +RESULT = binary_exponentiation(BASE, POWER) +print("{}^({}) : {}".format(BASE, POWER, RESULT)) diff --git a/maths/Find_Min.py b/maths/Find_Min.py index 86207984e..c720da268 100644 --- a/maths/Find_Min.py +++ b/maths/Find_Min.py @@ -1,12 +1,17 @@ -def main(): - def findMin(x): - minNum = x[0] - for i in x: - if minNum > i: - minNum = i - return minNum +"""Find Minimum Number in a List.""" + + +def main(): + """Find Minimum Number in a List.""" + def find_min(x): + min_num = x[0] + for i in x: + if min_num > i: + min_num = i + return min_num + + print(find_min([0, 1, 2, 3, 4, 5, -3, 24, -56])) # = -56 - print(findMin([0,1,2,3,4,5,-3,24,-56])) # = -56 if __name__ == '__main__': main() diff --git a/maths/Prime_Check.py b/maths/Prime_Check.py index 8c5c18168..9249834dc 100644 --- a/maths/Prime_Check.py +++ b/maths/Prime_Check.py @@ -1,9 +1,13 @@ +"""Prime Check.""" + import math import unittest -def primeCheck(number): +def prime_check(number): """ + Check to See if a Number is Prime. + A number is prime if it has exactly two dividers: 1 and itself. """ if number < 2: @@ -24,31 +28,30 @@ def primeCheck(number): class Test(unittest.TestCase): def test_primes(self): - self.assertTrue(primeCheck(2)) - self.assertTrue(primeCheck(3)) - self.assertTrue(primeCheck(5)) - self.assertTrue(primeCheck(7)) - self.assertTrue(primeCheck(11)) - self.assertTrue(primeCheck(13)) - self.assertTrue(primeCheck(17)) - self.assertTrue(primeCheck(19)) - self.assertTrue(primeCheck(23)) - self.assertTrue(primeCheck(29)) + self.assertTrue(prime_check(2)) + self.assertTrue(prime_check(3)) + self.assertTrue(prime_check(5)) + self.assertTrue(prime_check(7)) + self.assertTrue(prime_check(11)) + self.assertTrue(prime_check(13)) + self.assertTrue(prime_check(17)) + self.assertTrue(prime_check(19)) + self.assertTrue(prime_check(23)) + self.assertTrue(prime_check(29)) def test_not_primes(self): - self.assertFalse(primeCheck(-19), - "Negative numbers are not prime.") - self.assertFalse(primeCheck(0), - "Zero doesn't have any divider, primes must have two") - self.assertFalse(primeCheck(1), - "One just have 1 divider, primes must have two.") - self.assertFalse(primeCheck(2 * 2)) - self.assertFalse(primeCheck(2 * 3)) - self.assertFalse(primeCheck(3 * 3)) - self.assertFalse(primeCheck(3 * 5)) - self.assertFalse(primeCheck(3 * 5 * 7)) + self.assertFalse(prime_check(-19), + "Negative numbers are not prime.") + self.assertFalse(prime_check(0), + "Zero doesn't have any divider, primes must have two") + self.assertFalse(prime_check(1), + "One just have 1 divider, primes must have two.") + self.assertFalse(prime_check(2 * 2)) + self.assertFalse(prime_check(2 * 3)) + self.assertFalse(prime_check(3 * 3)) + self.assertFalse(prime_check(3 * 5)) + self.assertFalse(prime_check(3 * 5 * 7)) if __name__ == '__main__': unittest.main() - diff --git a/maths/abs.py b/maths/abs.py index 624823fc1..2734e58ce 100644 --- a/maths/abs.py +++ b/maths/abs.py @@ -1,24 +1,25 @@ """Absolute Value.""" -def absVal(num): +def abs_val(num): """ Find the absolute value of a number. - >>absVal(-5) + >>abs_val(-5) 5 - >>absVal(0) + >>abs_val(0) 0 """ if num < 0: return -num - else: - return num + + # Returns if number is not < 0 + return num def main(): """Print absolute value of -34.""" - print(absVal(-34)) # = 34 + print(abs_val(-34)) # = 34 if __name__ == '__main__': diff --git a/maths/extended_euclidean_algorithm.py b/maths/extended_euclidean_algorithm.py index f5a3cc88e..fc3798e7e 100644 --- a/maths/extended_euclidean_algorithm.py +++ b/maths/extended_euclidean_algorithm.py @@ -1,20 +1,38 @@ +""" +Extended Euclidean Algorithm. + +Finds 2 numbers a and b such that it satisfies +the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) +""" + # @Author: S. Sharma # @Date: 2019-02-25T12:08:53-06:00 # @Email: silentcat@protonmail.com -# @Last modified by: silentcat -# @Last modified time: 2019-02-26T07:07:38-06:00 +# @Last modified by: PatOnTheBack +# @Last modified time: 2019-07-05 import sys -# Finds 2 numbers a and b such that it satisfies -# the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) + def extended_euclidean_algorithm(m, n): - a = 0; aprime = 1; b = 1; bprime = 0 - q = 0; r = 0 + """ + Extended Euclidean Algorithm. + + Finds 2 numbers a and b such that it satisfies + the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) + """ + a = 0 + a_prime = 1 + b = 1 + b_prime = 0 + q = 0 + r = 0 if m > n: - c = m; d = n + c = m + d = n else: - c = n; d = m + c = n + d = m while True: q = int(c / d) @@ -24,22 +42,24 @@ def extended_euclidean_algorithm(m, n): c = d d = r - t = aprime - aprime = a - a = t - q*a + t = a_prime + a_prime = a + a = t - q * a - t = bprime - bprime = b - b = t - q*b + t = b_prime + b_prime = b + b = t - q * b pair = None if m > n: - pair = (a,b) + pair = (a, b) else: - pair = (b,a) + pair = (b, a) return pair + def main(): + """Call Extended Euclidean Algorithm.""" if len(sys.argv) < 3: print('2 integer arguments required') exit(1) @@ -47,5 +67,6 @@ def main(): n = int(sys.argv[2]) print(extended_euclidean_algorithm(m, n)) + if __name__ == '__main__': main() diff --git a/maths/fermat_little_theorem.py b/maths/fermat_little_theorem.py index 93af98684..8cf60dafe 100644 --- a/maths/fermat_little_theorem.py +++ b/maths/fermat_little_theorem.py @@ -5,13 +5,13 @@ def binary_exponentiation(a, n, mod): - + if (n == 0): return 1 - + elif (n % 2 == 1): return (binary_exponentiation(a, n - 1, mod) * a) % mod - + else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod diff --git a/maths/greater_common_divisor.py b/maths/greater_common_divisor.py index 15adaca1f..adc7811e8 100644 --- a/maths/greater_common_divisor.py +++ b/maths/greater_common_divisor.py @@ -1,15 +1,25 @@ -# Greater Common Divisor - https://en.wikipedia.org/wiki/Greatest_common_divisor +""" +Greater Common Divisor. + +Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor +""" + + def gcd(a, b): + """Calculate Greater Common Divisor (GCD).""" return b if a == 0 else gcd(b % a, a) + def main(): + """Call GCD Function.""" try: nums = input("Enter two Integers separated by comma (,): ").split(',') - num1 = int(nums[0]); num2 = int(nums[1]) + num_1 = int(nums[0]) + num_2 = int(nums[1]) except (IndexError, UnboundLocalError, ValueError): print("Wrong Input") - print(f"gcd({num1}, {num2}) = {gcd(num1, num2)}") + print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") + if __name__ == '__main__': main() - diff --git a/maths/modular_exponential.py b/maths/modular_exponential.py index b3f4c00bd..750de7cba 100644 --- a/maths/modular_exponential.py +++ b/maths/modular_exponential.py @@ -1,20 +1,25 @@ -def modularExponential(base, power, mod): - if power < 0: - return -1 - base %= mod - result = 1 +"""Modular Exponential.""" - while power > 0: - if power & 1: - result = (result * base) % mod - power = power >> 1 - base = (base * base) % mod - return result + +def modular_exponential(base, power, mod): + """Calculate Modular Exponential.""" + if power < 0: + return -1 + base %= mod + result = 1 + + while power > 0: + if power & 1: + result = (result * base) % mod + power = power >> 1 + base = (base * base) % mod + return result def main(): - print(modularExponential(3, 200, 13)) + """Call Modular Exponential Function.""" + print(modular_exponential(3, 200, 13)) if __name__ == '__main__': - main() + main() diff --git a/maths/segmented_sieve.py b/maths/segmented_sieve.py index 52ca6fbe6..b15ec2480 100644 --- a/maths/segmented_sieve.py +++ b/maths/segmented_sieve.py @@ -1,46 +1,51 @@ +"""Segmented Sieve.""" + import math + def sieve(n): + """Segmented Sieve.""" in_prime = [] start = 2 - end = int(math.sqrt(n)) # Size of every segment + end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] - - while(start <= end): - if temp[start] == True: + + while start <= end: + if temp[start] is True: in_prime.append(start) - for i in range(start*start, end+1, start): - if temp[i] == True: + for i in range(start * start, end + 1, start): + if temp[i] is True: temp[i] = False start += 1 prime += in_prime - + low = end + 1 high = low + end - 1 if high > n: high = n - - while(low <= n): - temp = [True] * (high-low+1) + + while low <= n: + temp = [True] * (high - low + 1) for each in in_prime: - + t = math.floor(low / each) * each if t < low: t += each - - for j in range(t, high+1, each): + + for j in range(t, high + 1, each): temp[j - low] = False - + for j in range(len(temp)): - if temp[j] == True: - prime.append(j+low) - + if temp[j] is True: + prime.append(j + low) + low = high + 1 high = low + end - 1 if high > n: high = n - + return prime -print(sieve(10**6)) \ No newline at end of file + +print(sieve(10**6)) diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index 26c17fa6f..11c123693 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -1,24 +1,29 @@ +"""Sieve of Eratosthones.""" + import math -n = int(input("Enter n: ")) + +N = int(input("Enter n: ")) + def sieve(n): - l = [True] * (n+1) + """Sieve of Eratosthones.""" + l = [True] * (n + 1) prime = [] start = 2 - end = int(math.sqrt(n)) - while(start <= end): - if l[start] == True: + end = int(math.sqrt(n)) + while start <= end: + if l[start] is True: prime.append(start) - for i in range(start*start, n+1, start): - if l[i] == True: + for i in range(start * start, n + 1, start): + if l[i] is True: l[i] = False start += 1 - - for j in range(end+1,n+1): - if l[j] == True: + + for j in range(end + 1, n + 1): + if l[j] is True: prime.append(j) - + return prime -print(sieve(n)) - + +print(sieve(N)) diff --git a/maths/simpson_rule.py b/maths/simpson_rule.py index 091c86c17..2b237d2e1 100644 --- a/maths/simpson_rule.py +++ b/maths/simpson_rule.py @@ -1,49 +1,49 @@ -''' +""" Numerical integration or quadrature for a smooth function f with known values at x_i -This method is the classical approch of suming 'Equally Spaced Abscissas' +This method is the classical approch of suming 'Equally Spaced Abscissas' -method 2: +method 2: "Simpson Rule" -''' +""" from __future__ import print_function def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) - h = (boundary[1] - boundary[0]) / steps - a = boundary[0] - b = boundary[1] - x_i = makePoints(a,b,h) - y = 0.0 - y += (h/3.0)*f(a) - cnt = 2 - for i in x_i: - y += (h/3)*(4-2*(cnt%2))*f(i) - cnt += 1 - y += (h/3.0)*f(b) - return y + h = (boundary[1] - boundary[0]) / steps + a = boundary[0] + b = boundary[1] + x_i = make_points(a,b,h) + y = 0.0 + y += (h/3.0)*f(a) + cnt = 2 + for i in x_i: + y += (h/3)*(4-2*(cnt%2))*f(i) + cnt += 1 + y += (h/3.0)*f(b) + return y -def makePoints(a,b,h): - x = a + h - while x < (b-h): - yield x - x = x + h +def make_points(a,b,h): + x = a + h + while x < (b-h): + yield x + x = x + h def f(x): #enter your function here - y = (x-0)*(x-0) - return y + y = (x-0)*(x-0) + return y def main(): - a = 0.0 #Lower bound of integration - b = 1.0 #Upper bound of integration - steps = 10.0 #define number of steps or resolution - boundary = [a, b] #define boundary of integration - y = method_2(boundary, steps) - print('y = {0}'.format(y)) + a = 0.0 #Lower bound of integration + b = 1.0 #Upper bound of integration + steps = 10.0 #define number of steps or resolution + boundary = [a, b] #define boundary of integration + y = method_2(boundary, steps) + print('y = {0}'.format(y)) if __name__ == '__main__': main() diff --git a/maths/trapezoidal_rule.py b/maths/trapezoidal_rule.py index 52310c1ed..789f263c6 100644 --- a/maths/trapezoidal_rule.py +++ b/maths/trapezoidal_rule.py @@ -1,12 +1,12 @@ -''' +""" Numerical integration or quadrature for a smooth function f with known values at x_i -This method is the classical approch of suming 'Equally Spaced Abscissas' +This method is the classical approch of suming 'Equally Spaced Abscissas' -method 1: +method 1: "extended trapezoidal rule" -''' +""" from __future__ import print_function def method_1(boundary, steps): @@ -15,21 +15,21 @@ def method_1(boundary, steps): h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] - x_i = makePoints(a,b,h) - y = 0.0 + x_i = make_points(a,b,h) + y = 0.0 y += (h/2.0)*f(a) for i in x_i: #print(i) y += h*f(i) - y += (h/2.0)*f(b) - return y + y += (h/2.0)*f(b) + return y -def makePoints(a,b,h): - x = a + h +def make_points(a,b,h): + x = a + h while x < (b-h): yield x x = x + h - + def f(x): #enter your function here y = (x-0)*(x-0) return y @@ -37,7 +37,7 @@ def f(x): #enter your function here def main(): a = 0.0 #Lower bound of integration b = 1.0 #Upper bound of integration - steps = 10.0 #define number of steps or resolution + steps = 10.0 #define number of steps or resolution boundary = [a, b] #define boundary of integration y = method_1(boundary, steps) print('y = {0}'.format(y)) diff --git a/maths/volume.py b/maths/volume.py new file mode 100644 index 000000000..171bc538f --- /dev/null +++ b/maths/volume.py @@ -0,0 +1,100 @@ +""" +Find Volumes of Various Shapes. + +Wikipedia reference: https://en.wikipedia.org/wiki/Volume +""" + +from math import pi + +PI = pi + + +def vol_cube(side_length): + """Calculate the Volume of a Cube.""" + # Cube side_length. + return float(side_length ** 3) + + +def vol_cuboid(width, height, length): + """Calculate the Volume of a Cuboid.""" + # Multiply lengths together. + return float(width * height * length) + + +def vol_cone(area_of_base, height): + """ + Calculate the Volume of a Cone. + + Wikipedia reference: https://en.wikipedia.org/wiki/Cone + volume = (1/3) * area_of_base * height + """ + return (float(1) / 3) * area_of_base * height + + +def vol_right_circ_cone(radius, height): + """ + Calculate the Volume of a Right Circular Cone. + + Wikipedia reference: https://en.wikipedia.org/wiki/Cone + volume = (1/3) * pi * radius^2 * height + """ + + import math + + return (float(1) / 3) * PI * (radius ** 2) * height + + +def vol_prism(area_of_base, height): + """ + Calculate the Volume of a Prism. + + V = Bh + Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) + """ + return float(area_of_base * height) + + +def vol_pyramid(area_of_base, height): + """ + Calculate the Volume of a Prism. + + V = (1/3) * Bh + Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) + """ + return (float(1) / 3) * area_of_base * height + + +def vol_sphere(radius): + """ + Calculate the Volume of a Sphere. + + V = (4/3) * pi * r^3 + Wikipedia reference: https://en.wikipedia.org/wiki/Sphere + """ + return (float(4) / 3) * PI * radius ** 3 + + +def vol_circular_cylinder(radius, height): + """Calculate the Volume of a Circular Cylinder. + + Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder + volume = pi * radius^2 * height + """ + return PI * radius ** 2 * height + + +def main(): + """Print the Results of Various Volume Calculations.""" + print("Volumes:") + print("Cube: " + str(vol_cube(2))) # = 8 + print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 + print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 + print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 + print("Prism: " + str(vol_prism(2, 2))) # = 4 + print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 + print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 + print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 + + +if __name__ == "__main__": + main()