mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
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:
parent
2ad5be9919
commit
897f1d0fb4
|
@ -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))
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
|
13
maths/abs.py
13
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__':
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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
|
||||
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))
|
|
@ -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))
|
||||
|
|
|
@ -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,43 +7,43 @@ This method is the classical approch of suming 'Equally Spaced Abscissas'
|
|||
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()
|
||||
|
|
|
@ -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
100
maths/volume.py
Normal 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()
|
Loading…
Reference in New Issue
Block a user