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 64c19f7a6c.

* Update lucasSeries.py
This commit is contained in:
PatOnTheBack 2019-07-10 16:09:24 -04:00 committed by cclauss
parent 2ad5be9919
commit 897f1d0fb4
13 changed files with 317 additions and 160 deletions

View File

@ -1,6 +1,9 @@
"""Binary Exponentiation."""
# Author : Junth Basnet # Author : Junth Basnet
# Time Complexity : O(logn) # Time Complexity : O(logn)
def binary_exponentiation(a, n): def binary_exponentiation(a, n):
if (n == 0): if (n == 0):
@ -15,11 +18,10 @@ def binary_exponentiation(a, n):
try: try:
base = int(input('Enter Base : ')) BASE = int(input('Enter Base : '))
power = int(input("Enter Power : ")) POWER = int(input("Enter Power : "))
except ValueError: except ValueError:
print("Invalid literal for integer") print("Invalid literal for integer")
result = binary_exponentiation(base, power) RESULT = binary_exponentiation(BASE, POWER)
print("{}^({}) : {}".format(base, power, result)) print("{}^({}) : {}".format(BASE, POWER, RESULT))

View File

@ -1,12 +1,17 @@
def main(): """Find Minimum Number in a List."""
def findMin(x):
minNum = x[0]
for i in x: def main():
if minNum > i: """Find Minimum Number in a List."""
minNum = i def find_min(x):
return minNum 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__': if __name__ == '__main__':
main() main()

View File

@ -1,9 +1,13 @@
"""Prime Check."""
import math import math
import unittest 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. A number is prime if it has exactly two dividers: 1 and itself.
""" """
if number < 2: if number < 2:
@ -24,31 +28,30 @@ def primeCheck(number):
class Test(unittest.TestCase): class Test(unittest.TestCase):
def test_primes(self): def test_primes(self):
self.assertTrue(primeCheck(2)) self.assertTrue(prime_check(2))
self.assertTrue(primeCheck(3)) self.assertTrue(prime_check(3))
self.assertTrue(primeCheck(5)) self.assertTrue(prime_check(5))
self.assertTrue(primeCheck(7)) self.assertTrue(prime_check(7))
self.assertTrue(primeCheck(11)) self.assertTrue(prime_check(11))
self.assertTrue(primeCheck(13)) self.assertTrue(prime_check(13))
self.assertTrue(primeCheck(17)) self.assertTrue(prime_check(17))
self.assertTrue(primeCheck(19)) self.assertTrue(prime_check(19))
self.assertTrue(primeCheck(23)) self.assertTrue(prime_check(23))
self.assertTrue(primeCheck(29)) self.assertTrue(prime_check(29))
def test_not_primes(self): def test_not_primes(self):
self.assertFalse(primeCheck(-19), self.assertFalse(prime_check(-19),
"Negative numbers are not prime.") "Negative numbers are not prime.")
self.assertFalse(primeCheck(0), self.assertFalse(prime_check(0),
"Zero doesn't have any divider, primes must have two") "Zero doesn't have any divider, primes must have two")
self.assertFalse(primeCheck(1), self.assertFalse(prime_check(1),
"One just have 1 divider, primes must have two.") "One just have 1 divider, primes must have two.")
self.assertFalse(primeCheck(2 * 2)) self.assertFalse(prime_check(2 * 2))
self.assertFalse(primeCheck(2 * 3)) self.assertFalse(prime_check(2 * 3))
self.assertFalse(primeCheck(3 * 3)) self.assertFalse(prime_check(3 * 3))
self.assertFalse(primeCheck(3 * 5)) self.assertFalse(prime_check(3 * 5))
self.assertFalse(primeCheck(3 * 5 * 7)) self.assertFalse(prime_check(3 * 5 * 7))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -1,24 +1,25 @@
"""Absolute Value.""" """Absolute Value."""
def absVal(num): def abs_val(num):
""" """
Find the absolute value of a number. Find the absolute value of a number.
>>absVal(-5) >>abs_val(-5)
5 5
>>absVal(0) >>abs_val(0)
0 0
""" """
if num < 0: if num < 0:
return -num return -num
else:
# Returns if number is not < 0
return num return num
def main(): def main():
"""Print absolute value of -34.""" """Print absolute value of -34."""
print(absVal(-34)) # = 34 print(abs_val(-34)) # = 34
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -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 <silentcat> # @Author: S. Sharma <silentcat>
# @Date: 2019-02-25T12:08:53-06:00 # @Date: 2019-02-25T12:08:53-06:00
# @Email: silentcat@protonmail.com # @Email: silentcat@protonmail.com
# @Last modified by: silentcat # @Last modified by: PatOnTheBack
# @Last modified time: 2019-02-26T07:07:38-06:00 # @Last modified time: 2019-07-05
import sys 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): 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: if m > n:
c = m; d = n c = m
d = n
else: else:
c = n; d = m c = n
d = m
while True: while True:
q = int(c / d) q = int(c / d)
@ -24,12 +42,12 @@ def extended_euclidean_algorithm(m, n):
c = d c = d
d = r d = r
t = aprime t = a_prime
aprime = a a_prime = a
a = t - q * a a = t - q * a
t = bprime t = b_prime
bprime = b b_prime = b
b = t - q * b b = t - q * b
pair = None pair = None
@ -39,7 +57,9 @@ def extended_euclidean_algorithm(m, n):
pair = (b, a) pair = (b, a)
return pair return pair
def main(): def main():
"""Call Extended Euclidean Algorithm."""
if len(sys.argv) < 3: if len(sys.argv) < 3:
print('2 integer arguments required') print('2 integer arguments required')
exit(1) exit(1)
@ -47,5 +67,6 @@ def main():
n = int(sys.argv[2]) n = int(sys.argv[2])
print(extended_euclidean_algorithm(m, n)) print(extended_euclidean_algorithm(m, n))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -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): def gcd(a, b):
"""Calculate Greater Common Divisor (GCD)."""
return b if a == 0 else gcd(b % a, a) return b if a == 0 else gcd(b % a, a)
def main(): def main():
"""Call GCD Function."""
try: try:
nums = input("Enter two Integers separated by comma (,): ").split(',') 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): except (IndexError, UnboundLocalError, ValueError):
print("Wrong Input") 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__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,8 @@
def modularExponential(base, power, mod): """Modular Exponential."""
def modular_exponential(base, power, mod):
"""Calculate Modular Exponential."""
if power < 0: if power < 0:
return -1 return -1
base %= mod base %= mod
@ -13,7 +17,8 @@ def modularExponential(base, power, mod):
def main(): def main():
print(modularExponential(3, 200, 13)) """Call Modular Exponential Function."""
print(modular_exponential(3, 200, 13))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,17 +1,21 @@
"""Segmented Sieve."""
import math import math
def sieve(n): def sieve(n):
"""Segmented Sieve."""
in_prime = [] in_prime = []
start = 2 start = 2
end = int(math.sqrt(n)) # Size of every segment end = int(math.sqrt(n)) # Size of every segment
temp = [True] * (end + 1) temp = [True] * (end + 1)
prime = [] prime = []
while(start <= end): while start <= end:
if temp[start] == True: if temp[start] is True:
in_prime.append(start) in_prime.append(start)
for i in range(start * start, end + 1, start): for i in range(start * start, end + 1, start):
if temp[i] == True: if temp[i] is True:
temp[i] = False temp[i] = False
start += 1 start += 1
prime += in_prime prime += in_prime
@ -21,7 +25,7 @@ def sieve(n):
if high > n: if high > n:
high = n high = n
while(low <= n): while low <= n:
temp = [True] * (high - low + 1) temp = [True] * (high - low + 1)
for each in in_prime: for each in in_prime:
@ -33,7 +37,7 @@ def sieve(n):
temp[j - low] = False temp[j - low] = False
for j in range(len(temp)): for j in range(len(temp)):
if temp[j] == True: if temp[j] is True:
prime.append(j + low) prime.append(j + low)
low = high + 1 low = high + 1
@ -43,4 +47,5 @@ def sieve(n):
return prime return prime
print(sieve(10**6)) print(sieve(10**6))

View File

@ -1,24 +1,29 @@
"""Sieve of Eratosthones."""
import math import math
n = int(input("Enter n: "))
N = int(input("Enter n: "))
def sieve(n): def sieve(n):
"""Sieve of Eratosthones."""
l = [True] * (n + 1) l = [True] * (n + 1)
prime = [] prime = []
start = 2 start = 2
end = int(math.sqrt(n)) end = int(math.sqrt(n))
while(start <= end): while start <= end:
if l[start] == True: if l[start] is True:
prime.append(start) prime.append(start)
for i in range(start * start, n + 1, start): for i in range(start * start, n + 1, start):
if l[i] == True: if l[i] is True:
l[i] = False l[i] = False
start += 1 start += 1
for j in range(end + 1, n + 1): for j in range(end + 1, n + 1):
if l[j] == True: if l[j] is True:
prime.append(j) prime.append(j)
return prime return prime
print(sieve(n))
print(sieve(N))

View File

@ -1,5 +1,5 @@
''' """
Numerical integration or quadrature for a smooth function f with known values at x_i 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'
@ -7,7 +7,7 @@ This method is the classical approch of suming 'Equally Spaced Abscissas'
method 2: method 2:
"Simpson Rule" "Simpson Rule"
''' """
from __future__ import print_function from __future__ import print_function
@ -17,7 +17,7 @@ def method_2(boundary, steps):
h = (boundary[1] - boundary[0]) / steps h = (boundary[1] - boundary[0]) / steps
a = boundary[0] a = boundary[0]
b = boundary[1] b = boundary[1]
x_i = makePoints(a,b,h) x_i = make_points(a,b,h)
y = 0.0 y = 0.0
y += (h/3.0)*f(a) y += (h/3.0)*f(a)
cnt = 2 cnt = 2
@ -27,7 +27,7 @@ def method_2(boundary, steps):
y += (h/3.0)*f(b) y += (h/3.0)*f(b)
return y return y
def makePoints(a,b,h): def make_points(a,b,h):
x = a + h x = a + h
while x < (b-h): while x < (b-h):
yield x yield x

View File

@ -1,4 +1,4 @@
''' """
Numerical integration or quadrature for a smooth function f with known values at x_i 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'
@ -6,7 +6,7 @@ This method is the classical approch of suming 'Equally Spaced Abscissas'
method 1: method 1:
"extended trapezoidal rule" "extended trapezoidal rule"
''' """
from __future__ import print_function from __future__ import print_function
def method_1(boundary, steps): def method_1(boundary, steps):
@ -15,7 +15,7 @@ def method_1(boundary, steps):
h = (boundary[1] - boundary[0]) / steps h = (boundary[1] - boundary[0]) / steps
a = boundary[0] a = boundary[0]
b = boundary[1] b = boundary[1]
x_i = makePoints(a,b,h) x_i = make_points(a,b,h)
y = 0.0 y = 0.0
y += (h/2.0)*f(a) y += (h/2.0)*f(a)
for i in x_i: for i in x_i:
@ -24,7 +24,7 @@ def method_1(boundary, steps):
y += (h/2.0)*f(b) y += (h/2.0)*f(b)
return y return y
def makePoints(a,b,h): def make_points(a,b,h):
x = a + h x = a + h
while x < (b-h): while x < (b-h):
yield x yield x

100
maths/volume.py Normal file
View File

@ -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()