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,25 +1,27 @@
#Author : Junth Basnet """Binary Exponentiation."""
#Time Complexity : O(logn)
# Author : Junth Basnet
# Time Complexity : O(logn)
def binary_exponentiation(a, n): def binary_exponentiation(a, n):
if (n == 0): if (n == 0):
return 1 return 1
elif (n % 2 == 1): elif (n % 2 == 1):
return binary_exponentiation(a, n - 1) * a return binary_exponentiation(a, n - 1) * a
else: else:
b = binary_exponentiation(a, n / 2) b = binary_exponentiation(a, n / 2)
return b * b 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) try:
print("{}^({}) : {}".format(base, power, result)) 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))

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:
return num # Returns if number is not < 0
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,22 +42,24 @@ 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
if m > n: if m > n:
pair = (a,b) pair = (a, b)
else: else:
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

@ -5,13 +5,13 @@
def binary_exponentiation(a, n, mod): def binary_exponentiation(a, n, mod):
if (n == 0): if (n == 0):
return 1 return 1
elif (n % 2 == 1): elif (n % 2 == 1):
return (binary_exponentiation(a, n - 1, mod) * a) % mod return (binary_exponentiation(a, n - 1, mod) * a) % mod
else: else:
b = binary_exponentiation(a, n / 2, mod) b = binary_exponentiation(a, n / 2, mod)
return (b * b) % mod return (b * b) % mod

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,20 +1,25 @@
def modularExponential(base, power, mod): """Modular Exponential."""
if power < 0:
return -1
base %= mod
result = 1
while power > 0:
if power & 1: def modular_exponential(base, power, mod):
result = (result * base) % mod """Calculate Modular Exponential."""
power = power >> 1 if power < 0:
base = (base * base) % mod return -1
return result 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(): def main():
print(modularExponential(3, 200, 13)) """Call Modular Exponential Function."""
print(modular_exponential(3, 200, 13))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,46 +1,51 @@
"""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
low = end + 1 low = end + 1
high = low + end - 1 high = low + end - 1
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:
t = math.floor(low / each) * each t = math.floor(low / each) * each
if t < low: if t < low:
t += each t += each
for j in range(t, high+1, each): for j in range(t, high + 1, each):
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
high = low + end - 1 high = low + end - 1
if high > n: if high > n:
high = n high = 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):
l = [True] * (n+1) """Sieve of Eratosthones."""
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,49 +1,49 @@
''' """
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'
method 2: method 2:
"Simpson Rule" "Simpson Rule"
''' """
from __future__ import print_function from __future__ import print_function
def method_2(boundary, steps): def method_2(boundary, steps):
# "Simpson Rule" # "Simpson Rule"
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
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
for i in x_i: for i in x_i:
y += (h/3)*(4-2*(cnt%2))*f(i) y += (h/3)*(4-2*(cnt%2))*f(i)
cnt += 1 cnt += 1
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
x = x + h x = x + h
def f(x): #enter your function here def f(x): #enter your function here
y = (x-0)*(x-0) y = (x-0)*(x-0)
return y return y
def main(): def main():
a = 0.0 #Lower bound of integration a = 0.0 #Lower bound of integration
b = 1.0 #Upper 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 boundary = [a, b] #define boundary of integration
y = method_2(boundary, steps) y = method_2(boundary, steps)
print('y = {0}'.format(y)) print('y = {0}'.format(y))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,12 +1,12 @@
''' """
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'
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,21 +15,21 @@ 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:
#print(i) #print(i)
y += h*f(i) y += h*f(i)
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
x = x + h x = x + h
def f(x): #enter your function here def f(x): #enter your function here
y = (x-0)*(x-0) y = (x-0)*(x-0)
return y return y
@ -37,7 +37,7 @@ def f(x): #enter your function here
def main(): def main():
a = 0.0 #Lower bound of integration a = 0.0 #Lower bound of integration
b = 1.0 #Upper 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 boundary = [a, b] #define boundary of integration
y = method_1(boundary, steps) y = method_1(boundary, steps)
print('y = {0}'.format(y)) print('y = {0}'.format(y))

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