Skip to content

Commit aa11f16

Browse files
authored
Sync Fork - TheAlgorithms/master
Sync Fork
2 parents 49fc9a1 + d34b072 commit aa11f16

39 files changed

+415
-218
lines changed

Maths/3n+1.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def main():
2+
def n31(a):# a = initial number
3+
c = 0
4+
l = [a]
5+
while a != 1:
6+
if a % 2 == 0:#if even divide it by 2
7+
a = a // 2
8+
elif a % 2 == 1:#if odd 3n+1
9+
a = 3*a +1
10+
c += 1#counter
11+
l += [a]
12+
13+
return l , c
14+
print(n31(43))
15+
print(n31(98)[0][-1])# = a
16+
print("It took {0} steps.".format(n31(13)[1]))#optional finish
17+
18+
if __name__ == '__main__':
19+
main()

Maths/FindMax.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
# NguyenU
22

3-
import math
43
def find_max(nums):
5-
max = 0
4+
max = nums[0]
65
for x in nums:
76
if x > max:
87
max = x

Maths/FindMin.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def main():
2+
def findMin(x):
3+
minNum = x[0]
4+
for i in x:
5+
if minNum > i:
6+
minNum = i
7+
return minNum
8+
9+
print(findMin([0,1,2,3,4,5,-3,24,-56])) # = -56
10+
11+
if __name__ == '__main__':
12+
main()

Maths/abs.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def absVal(num):
2+
"""
3+
Function to fins absolute value of numbers.
4+
>>>absVal(-5)
5+
5
6+
>>>absVal(0)
7+
0
8+
"""
9+
if num < 0:
10+
return -num
11+
else:
12+
return num
13+
14+
def main():
15+
print(absVal(-34)) # = 34
16+
17+
if __name__ == '__main__':
18+
main()

Maths/absMax.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from abs import absVal
2+
def absMax(x):
3+
"""
4+
>>>absMax([0,5,1,11])
5+
11
6+
>>absMax([3,-10,-2])
7+
-10
8+
"""
9+
j = x[0]
10+
for i in x:
11+
if absVal(i) < j:
12+
j = i
13+
return j
14+
#BUG: i is apparently a list, TypeError: '<' not supported between instances of 'list' and 'int' in absVal
15+
16+
17+
def main():
18+
a = [1,2,-11]
19+
print(absVal(a)) # = -11
20+
21+
if __name__ == '__main__':
22+
main()

Maths/absMin.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from abs import absVal
2+
def absMin(x):
3+
"""
4+
>>>absMin([0,5,1,11])
5+
0
6+
>>absMin([3,-10,-2])
7+
-2
8+
"""
9+
j = x[0]
10+
for i in x:
11+
if absVal(i) < j:
12+
j = i
13+
return j
14+
15+
def main():
16+
a = [1,2,-11]
17+
print(absMin(a)) # = 1
18+
19+
if __name__ == '__main__':
20+
main()

README.md

+41-38
Large diffs are not rendered by default.
Loading
Loading
Loading

analysis/compression_analysis/psnr.py

+27-26
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,39 @@
1-
import numpy as np
1+
"""
2+
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
3+
Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
4+
"""
5+
26
import math
7+
38
import cv2
9+
import numpy as np
410

5-
def Representational(r,g,b):
6-
return (0.299*r+0.287*g+0.114*b)
11+
def psnr(original, contrast):
12+
mse = np.mean((original - contrast) ** 2)
13+
if mse == 0:
14+
return 100
15+
PIXEL_MAX = 255.0
16+
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
17+
return PSNR
718

8-
def calculate(img):
9-
b,g,r = cv2.split(img)
10-
pixelAt = Representational(r,g,b)
11-
return pixelAt
1219

1320
def main():
14-
15-
#Loading images (orignal image and compressed image)
16-
orignal_image = cv2.imread('orignal_image.png',1)
17-
compressed_image = cv2.imread('compressed_image.png',1)
1821

19-
#Getting image height and width
20-
height,width = orignal_image.shape[:2]
22+
# Loading images (original image and compressed image)
23+
original = cv2.imread('original_image.png')
24+
contrast = cv2.imread('compressed_image.png', 1)
2125

22-
orignalPixelAt = calculate(orignal_image)
23-
compressedPixelAt = calculate(compressed_image)
26+
original2 = cv2.imread('PSNR-example-base.png')
27+
contrast2 = cv2.imread('PSNR-example-comp-10.jpg', 1)
2428

25-
diff = orignalPixelAt - compressedPixelAt
26-
error = np.sum(np.abs(diff) ** 2)
27-
28-
error = error/(height*width)
29-
30-
#MSR = error_sum/(height*width)
31-
PSNR = -(10*math.log10(error/(255*255)))
32-
33-
print("PSNR value is {}".format(PSNR))
29+
# Value expected: 29.73dB
30+
print("-- First Test --")
31+
print(f"PSNR value is {psnr(original, contrast)} dB")
32+
33+
# # Value expected: 31.53dB (Wikipedia Example)
34+
print("\n-- Second Test --")
35+
print(f"PSNR value is {psnr(original2, contrast2)} dB")
3436

3537

3638
if __name__ == '__main__':
37-
main()
38-
39+
main()

arithmetic_analysis/bisection.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
1515
return
1616
else:
1717
mid = (start + end) / 2
18-
while abs(start - mid) > 0.0000001: # until we achieve precise equals to 10^-7
18+
while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7
1919
if function(mid) == 0:
2020
return mid
2121
elif function(mid) * function(start) < 0:
@@ -29,5 +29,5 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
2929
def f(x):
3030
return math.pow(x, 3) - 2*x - 5
3131

32-
33-
print(bisection(f, 1, 1000))
32+
if __name__ == "__main__":
33+
print(bisection(f, 1, 1000))

arithmetic_analysis/intersection.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ def intersection(function,x0,x1): #function is the f we want to find its root an
55
x_n1 = x1
66
while True:
77
x_n2 = x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n)))
8-
if abs(x_n2 - x_n1)<0.00001 :
8+
if abs(x_n2 - x_n1) < 10**-5:
99
return x_n2
1010
x_n=x_n1
1111
x_n1=x_n2
1212

1313
def f(x):
14-
return math.pow(x,3)-2*x-5
14+
return math.pow(x , 3) - (2 * x) -5
1515

16-
print(intersection(f,3,3.5))
16+
if __name__ == "__main__":
17+
print(intersection(f,3,3.5))
+11-13
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1+
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
12
import numpy
23

34
def LUDecompose (table):
4-
#table that contains our data
5-
#table has to be a square array so we need to check first
5+
# Table that contains our data
6+
# Table has to be a square array so we need to check first
67
rows,columns=numpy.shape(table)
78
L=numpy.zeros((rows,columns))
89
U=numpy.zeros((rows,columns))
910
if rows!=columns:
10-
return
11+
return []
1112
for i in range (columns):
1213
for j in range(i-1):
1314
sum=0
@@ -22,13 +23,10 @@ def LUDecompose (table):
2223
U[i][j]=table[i][j]-sum1
2324
return L,U
2425

25-
26-
27-
28-
29-
30-
31-
matrix =numpy.array([[2,-2,1],[0,1,2],[5,3,1]])
32-
L,U = LUDecompose(matrix)
33-
print(L)
34-
print(U)
26+
if __name__ == "__main__":
27+
matrix =numpy.array([[2,-2,1],
28+
[0,1,2],
29+
[5,3,1]])
30+
L,U = LUDecompose(matrix)
31+
print(L)
32+
print(U)

arithmetic_analysis/newton_method.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
1+
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
2+
13
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
24
x_n=startingInt
35
while True:
46
x_n1=x_n-function(x_n)/function1(x_n)
5-
if abs(x_n-x_n1)<0.00001:
7+
if abs(x_n-x_n1) < 10**-5:
68
return x_n1
79
x_n=x_n1
810

911
def f(x):
10-
return (x**3)-2*x-5
12+
return (x**3) - (2 * x) -5
1113

1214
def f1(x):
13-
return 3*(x**2)-2
15+
return 3 * (x**2) -2
1416

15-
print(newton(f,f1,3))
17+
if __name__ == "__main__":
18+
print(newton(f,f1,3))

ciphers/base16.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import base64
2+
3+
def main():
4+
inp = input('->')
5+
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
6+
b16encoded = base64.b16encode(encoded) #b16encoded the encoded string
7+
print(b16encoded)
8+
print(base64.b16decode(b16encoded).decode('utf-8'))#decoded it
9+
10+
if __name__ == '__main__':
11+
main()

ciphers/base32.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import base64
2+
3+
def main():
4+
inp = input('->')
5+
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
6+
b32encoded = base64.b32encode(encoded) #b32encoded the encoded string
7+
print(b32encoded)
8+
print(base64.b32decode(b32encoded).decode('utf-8'))#decoded it
9+
10+
if __name__ == '__main__':
11+
main()

ciphers/base64_cipher.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import base64
2+
3+
def main():
4+
inp = input('->')
5+
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
6+
b64encoded = base64.b64encode(encoded) #b64encoded the encoded string
7+
print(b64encoded)
8+
print(base64.b64decode(b64encoded).decode('utf-8'))#decoded it
9+
10+
if __name__ == '__main__':
11+
main()

ciphers/base85.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import base64
2+
3+
def main():
4+
inp = input('->')
5+
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
6+
a85encoded = base64.a85encode(encoded) #a85encoded the encoded string
7+
print(a85encoded)
8+
print(base64.a85decode(a85encoded).decode('utf-8'))#decoded it
9+
10+
if __name__ == '__main__':
11+
main()

ciphers/caesar_cipher.py

+12-17
Original file line numberDiff line numberDiff line change
@@ -34,35 +34,30 @@ def brute_force(strng):
3434

3535

3636
def main():
37-
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
38-
print("1.Encrpyt")
39-
print("2.Decrypt")
40-
print("3.BruteForce")
41-
print("4.Quit")
4237
while True:
38+
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
39+
print("1.Encrpyt")
40+
print("2.Decrypt")
41+
print("3.BruteForce")
42+
print("4.Quit")
4343
choice = input("What would you like to do?: ")
4444
if choice not in ['1', '2', '3', '4']:
4545
print ("Invalid choice")
4646
elif choice == '1':
4747
strng = input("Please enter the string to be ecrypted: ")
48-
while True:
49-
key = int(input("Please enter off-set between 1-94: "))
50-
if key in range(1, 95):
51-
print (encrypt(strng, key))
52-
main()
48+
key = int(input("Please enter off-set between 1-94: "))
49+
if key in range(1, 95):
50+
print (encrypt(strng.lower(), key))
5351
elif choice == '2':
5452
strng = input("Please enter the string to be decrypted: ")
55-
while True:
56-
key = int(input("Please enter off-set between 1-94: "))
57-
if key > 0 and key <= 94:
58-
print(decrypt(strng, key))
59-
main()
53+
key = int(input("Please enter off-set between 1-94: "))
54+
if key > 0 and key <= 94:
55+
print(decrypt(strng, key))
6056
elif choice == '3':
6157
strng = input("Please enter the string to be decrypted: ")
6258
brute_force(strng)
6359
main()
6460
elif choice == '4':
6561
print ("Goodbye.")
66-
sys.exit()
67-
62+
break
6863
main()

data_structures/arrays.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
arr = [10, 20, 30, 40]
2-
arr[1] = 30
2+
arr[1] = 30 # set element 1 (20) of array to 30
33
print(arr)

data_structures/graph/dijkstra.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def minDist(mdist, vset, V):
2121
def Dijkstra(graph, V, src):
2222
mdist=[float('inf') for i in range(V)]
2323
vset = [False for i in range(V)]
24-
mdist[src] = 0.0;
24+
mdist[src] = 0.0
2525

2626
for i in range(V-1):
2727
u = minDist(mdist, vset, V)

data_structures/heap/heap.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def maxHeapify(self,node):
4040
def buildHeap(self,a):
4141
self.currsize = len(a)
4242
self.h = list(a)
43-
for i in range(self.currsize/2,-1,-1):
43+
for i in range(self.currsize//2,-1,-1):
4444
self.maxHeapify(i)
4545

4646
def getMax(self):

0 commit comments

Comments
 (0)