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,5 +1,8 @@
#Author : Junth Basnet
#Time Complexity : O(logn)
"""Binary Exponentiation."""
# Author : Junth Basnet
# Time Complexity : O(logn)
def binary_exponentiation(a, n):
@ -15,11 +18,10 @@ def binary_exponentiation(a, n):
try:
base = int(input('Enter Base : '))
power = int(input("Enter Power : "))
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))
print("Invalid literal for integer")
RESULT = binary_exponentiation(BASE, POWER)
print("{}^({}) : {}".format(BASE, POWER, RESULT))

View File

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

View File

@ -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),
self.assertFalse(prime_check(-19),
"Negative numbers are not prime.")
self.assertFalse(primeCheck(0),
self.assertFalse(prime_check(0),
"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.")
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(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()

View File

@ -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:
# 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__':

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

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

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

View File

@ -1,17 +1,21 @@
"""Segmented Sieve."""
import math
def sieve(n):
"""Segmented Sieve."""
in_prime = []
start = 2
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
@ -21,20 +25,20 @@ def sieve(n):
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
@ -43,4 +47,5 @@ def sieve(n):
return prime
print(sieve(10**6))

View File

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

View File

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

View File

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