Skip to content

Commit fc96dc2

Browse files
committed
fixed some of the issues and tests
1 parent 36e7263 commit fc96dc2

20 files changed

+429
-280
lines changed

2-Getting_Started/Python/count_inversions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def test_count_inversions(self):
6262
A = [2, 4, 6, 1, 3, 5]
6363
p = 0
6464
r = len(A) - 1
65-
self.assertEqual(count_inversions(A, p, r), 9)
65+
self.assertEqual(count_inversions(A, p, r), 6)
6666

6767
# Test with array [1, 2, 3, 4, 5, 6]
6868
A = [1, 2, 3, 4, 5, 6]

2-Getting_Started/Python/maximum_consequtive_difference.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def maximum_difference(z):
88
elements in a list z. If z has fewer than two elements, it returns None.
99
"""
1010
# initialize the maximum difference to a very small value
11-
c = -99999999999999
11+
c = -float('inf')
1212

1313
# iterate over each pair of consecutive elements in z
1414
for i in range(1, len(z)):
@@ -31,7 +31,7 @@ def test_maximum_difference(self):
3131

3232
# Test with a mixed list of numbers
3333
z = [1, 24, 5, 6, 7, 8, -232, 35, 5, 67]
34-
self.assertEqual(maximum_difference(z), 256)
34+
self.assertEqual(maximum_difference(z), 267)
3535

3636

3737
if __name__ == '__main__':

2-Getting_Started/Python/n_bit_array_add.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,29 @@ def bit_add(x, y):
77
This function performs binary addition on two bit strings x and y.
88
It returns a new bit string that represents the sum of x and y.
99
"""
10+
# make sure x is the longer bit string
11+
if len(y) > len(x):
12+
x, y = y, x
13+
1014
# initialize the result bit string with a zero at the end
1115
z = [0] * (len(x) + 1)
1216
c = 0 # carry bit
1317

1418
# iterate over the bits of x and y
1519
for i in range(len(x)):
20+
# get the bit values of x and y, or 0 if out of range
21+
xi = x[-i-1] if i < len(x) else 0
22+
yi = y[-i-1] if i < len(y) else 0
23+
1624
# compute the sum and carry bits
17-
c, z[i] = divmod(x[i] + y[i] + c, 2)
25+
c, z[-i-1] = divmod(xi + yi + c, 2)
1826

1927
# set the last bit of the result to the carry bit
20-
z[-1] = c
28+
z[0] = c
29+
30+
# remove leading zeros
31+
while len(z) > 1 and z[0] == 0:
32+
z = z[1:]
2133

2234
return z
2335

@@ -27,17 +39,17 @@ def test_bit_add(self):
2739
# Test with bit strings 101 and 111
2840
a = [1, 0, 1]
2941
b = [1, 1, 1]
30-
self.assertEqual(bit_add(a, b), [1, 0, 0, 0])
42+
self.assertEqual(bit_add(a, b), [1, 1, 0, 0])
3143

3244
# Test with bit strings 1100 and 101
3345
a = [1, 1, 0, 0]
3446
b = [1, 0, 1]
35-
self.assertEqual(bit_add(a, b), [1, 0, 1, 1])
47+
self.assertEqual(bit_add(a, b), [1, 0, 0, 0, 1])
3648

3749
# Test with bit strings 1010 and 1010
3850
a = [1, 0, 1, 0]
3951
b = [1, 0, 1, 0]
40-
self.assertEqual(bit_add(a, b), [0, 1, 0, 0, 1])
52+
self.assertEqual(bit_add(a, b), [1, 0, 1, 0, 0])
4153

4254

4355
if __name__ == '__main__':

2-Getting_Started/Python/sieve_of_eratosthenes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def sieve(n):
2020
k.append(j)
2121

2222
# return the list of composite numbers and primes
23-
return k, primes
23+
return list(set(k)), primes
2424

2525

2626
class TestSieve(unittest.TestCase):

2-Getting_Started/Python/three_two_difference.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class TestThreeTwo(unittest.TestCase):
2424
def test_three_two(self):
2525
self.assertEqual(three_two(0), 0)
2626
self.assertEqual(three_two(1), 1)
27-
self.assertEqual(three_two(10), 295245)
27+
self.assertEqual(three_two(10), 58025)
2828

2929

3030
if __name__ == '__main__':

3-Growth_of_Functions/Python/comparison_two_algorithms.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import time
22
import sys
3+
import numpy as np
34
import matplotlib.pyplot as plt
45

56
# Author: Robert Joseph
@@ -11,18 +12,19 @@ def compare_algorithms(algo1, algo2, input_sizes):
1112
space2 = []
1213

1314
for n in input_sizes:
15+
list_values = np.random.randint(0, 100, n)
1416
# measure time complexity
1517
start_time = time.time()
16-
algo1(n)
18+
algo1(list_values)
1719
time1.append(time.time() - start_time)
1820

1921
start_time = time.time()
20-
algo2(n)
22+
algo2(list_values)
2123
time2.append(time.time() - start_time)
2224

2325
# measure space complexity
24-
size1 = sys.getsizeof(algo1(n))
25-
size2 = sys.getsizeof(algo2(n))
26+
size1 = sys.getsizeof(algo1(list_values))
27+
size2 = sys.getsizeof(algo2(list_values))
2628
space1.append(size1)
2729
space2.append(size2)
2830

3-Growth_of_Functions/Python/document_distance.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import collections as c
22
import unittest
3+
import math
34

45
# Author: Robert Joseph
56

@@ -19,18 +20,22 @@ def document_distance_problem(s1, s2):
1920
t = s2.split()
2021

2122
# Create dictionaries to store the word counts
22-
d1 = dict(c.OrderedDict(c.Counter(l)))
23-
d2 = dict(c.OrderedDict(c.Counter(t)))
24-
23+
d1 = dict(c.Counter(l))
24+
d2 = dict(c.Counter(t))
25+
2526
# Compute the dot product of the two dictionaries
26-
final_dot = 0
27-
for (k1,v1) in d1.items():
28-
for (k2,v2) in d2.items():
29-
if k1 == k2:
30-
final_dot += v1*v2
31-
32-
# Divide by the product of the magnitudes to obtain the cosine similarity
33-
return (final_dot/(len(d1)*len(d2)))*100
27+
dot_product = 0
28+
for word in d1.keys():
29+
if word in d2:
30+
dot_product += d1[word] * d2[word]
31+
32+
# Compute the magnitude of each dictionary
33+
d1_magnitude = math.sqrt(sum(count**2 for count in d1.values()))
34+
d2_magnitude = math.sqrt(sum(count**2 for count in d2.values()))
35+
36+
# Compute the cosine similarity
37+
similarity = dot_product / (d1_magnitude * d2_magnitude)
38+
return similarity * 100
3439

3540

3641
class TestDocumentDistanceProblem(unittest.TestCase):

3-Growth_of_Functions/Python/plus_one.py

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,29 +9,15 @@ def plusOne(A):
99
1010
The time complexity of this function is O(n), where n is the length of the input array A. This is because the function iterates over each digit in the array at most once.
1111
"""
12-
c = 0
13-
t = -1
14-
choice = True
15-
while choice:
16-
c = A[t] % 10
17-
if c == 9 and len(A) == -t:
18-
# if the last digit is 9 and we've reached the left end of the array,
19-
# insert a new digit 1 at the beginning of the array
20-
A.insert(0,1)
21-
choice = False
22-
elif c != 9:
23-
# if the last digit is not 9, simply add 1 to it and exit the loop
24-
A[t] += 1
25-
choice = False
26-
else:
27-
# if the last digit is 9, set it to 0 and continue with the next digit
28-
A[t] = 0
29-
t = t - 1
30-
31-
# remove leading zeros
32-
for i in range(len(A)):
33-
if A[i] != 0:
34-
return A[i:]
12+
carry = 1
13+
for i in range(len(A)-1, -1, -1):
14+
A[i] += carry
15+
carry = A[i] // 10
16+
A[i] %= 10
17+
18+
if carry:
19+
A.insert(0, 1)
20+
3521
return A
3622

3723

4-Divide_and_Conquer/Python/2d_peak_greedy.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,16 @@ def max_peak(arr):
2525
class TestMaxPeak(unittest.TestCase):
2626
def test_max_peak(self):
2727
# Test with a peak in the center
28-
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
29-
self.assertEqual(max_peak(arr), 5)
28+
arr = [[1, 2, 3], [4, 12, 6], [7, 8, 9]]
29+
self.assertEqual(max_peak(arr), 12)
3030

3131
# Test with a peak in the top left corner
3232
arr = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
33-
self.assertEqual(max_peak(arr), 9)
33+
self.assertEqual(max_peak(arr), False)
3434

3535
# Test with no peak
3636
arr = [[1, 2, 3], [4, 5, 6], [3, 2, 1]]
37-
self.assertFalse(max_peak(arr))
37+
self.assertFalse(max_peak(arr), False)
3838

3939

4040
if __name__ == '__main__':

4-Divide_and_Conquer/Python/2d_peak_optimized.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,35 @@
22

33
# Author: Robert Joseph
44

5-
def peak_finding_2d(arr, f, l, mid):
5+
def peak_finding_2d(arr):
66
"""
77
This function finds a peak element in a 2D array arr.
88
A peak element is an element that is greater than or equal to its four neighbors,
99
which are the elements that are directly above, below, to the left, and to the right of it.
1010
The function assumes that the input array is not empty and has at least one peak element.
1111
12-
The time complexity of this function is O(m log n), where m is the number of rows and n is the number of columns in the input array. This is because the function recursively halves the search space along the middle column until it finds a peak element, and each recursion takes O(m) time to scan a column of the array.
12+
The time complexity of this function is O(m log n), where m is the number of rows and n is the number of columns in the input array. This is because the function recursively halves the search space along the longer dimension until it finds a peak element, and each recursion takes O(n) or O(m) time to scan a row or column of the array.
1313
"""
14-
# initialize the maximum element in the middle column and its index
14+
m = len(arr)
15+
n = len(arr[0])
16+
mid = n // 2
1517
element = -1000000000
1618
index = 0
17-
for i in range(len(arr)):
18-
# find the maximum element in the middle column
19+
20+
# Find the maximum element in the middle column
21+
for i in range(m):
1922
if arr[i][mid] > element:
20-
element = max(element, arr[i][mid])
23+
element = arr[i][mid]
2124
index = i
22-
# print the maximum element and its row index (for debugging purposes)
23-
print(element, index)
24-
# check if the maximum element is a peak element
25-
if mid == 0 or mid == len(arr[0])-1 or (arr[index][mid-1] <= element and element >= arr[index][mid+1]):
25+
26+
# Check if the maximum element is a peak element
27+
if (mid == 0 or arr[index][mid-1] <= element) and (mid == n-1 or arr[index][mid+1] <= element):
2628
return element
27-
# if not, recurse on the half of the array with the higher neighbor
28-
elif element <= arr[index][mid+1]:
29-
return peak_finding_2d(arr, f, l, mid + mid//2)
29+
elif mid > 0 and arr[index][mid-1] > element:
30+
# Recurse on the half of the array with the higher neighbor
31+
return peak_finding_2d([row[:mid] for row in arr])
3032
else:
31-
return peak_finding_2d(arr, f, l, mid - mid//2)
33+
return peak_finding_2d([row[mid+1:] for row in arr])
3234

3335

3436
class TestPeakFinding2D(unittest.TestCase):
@@ -37,20 +39,20 @@ def test_peak_finding_2d(self):
3739
arr = [ [ 1, 2, 3 ],
3840
[ 4, 5, 6 ],
3941
[ 7, 8, 9 ] ]
40-
self.assertEqual(peak_finding_2d(arr, 0, 2, 1), 5)
42+
self.assertEqual(peak_finding_2d(arr), 9)
4143

4244
# Test with a 3x3 array with a peak at the corner
4345
arr = [ [ 10, 8, 6 ],
4446
[ 9, 7, 5 ],
4547
[ 8, 6, 4 ] ]
46-
self.assertEqual(peak_finding_2d(arr, 0, 2, 1), 10)
48+
self.assertEqual(peak_finding_2d(arr), 10)
4749

4850
# Test with a 4x4 array with a peak at the edge
4951
arr = [ [ 10, 8, 10, 10 ],
5052
[ 14, 13, 12, 11 ],
5153
[ 15, 11, 4, 10 ],
5254
[ 16, 17, 19, 20 ] ]
53-
self.assertEqual(peak_finding_2d(arr, 0, 3, 1), 17)
55+
self.assertEqual(peak_finding_2d(arr), 20)
5456

5557

5658
if __name__ == '__main__':

0 commit comments

Comments
 (0)