Skip to content

Misc fixes across multiple algorithms #6912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Oct 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compression/huffman.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def parse_file(file_path: str) -> list[Letter]:
c = f.read(1)
if not c:
break
chars[c] = chars[c] + 1 if c in chars.keys() else 1
chars[c] = chars[c] + 1 if c in chars else 1
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)


Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def is_palindrome_dict(head):
d = {}
pos = 0
while head:
if head.val in d.keys():
if head.val in d:
d[head.val].append(pos)
else:
d[head.val] = [pos]
Expand Down
2 changes: 1 addition & 1 deletion digital_image_processing/filters/local_binary_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)
)


if __name__ == "main":
if __name__ == "__main__":

# Reading the image and converting it to grayscale.
image = cv2.imread(
Expand Down
6 changes: 1 addition & 5 deletions fuzzy_logic/fuzzy_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@
- 3.5
"""
import numpy as np

try:
import skfuzzy as fuzz
except ImportError:
fuzz = None
import skfuzzy as fuzz

if __name__ == "__main__":
# Create universe of discourse in Python using linspace ()
Expand Down
4 changes: 2 additions & 2 deletions graphs/dijkstra_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ def add_edge(self, u, v, w):
# Edge going from node u to v and v to u with weight w
# u (w)-> v, v (w) -> u
# Check if u already in graph
if u in self.adjList.keys():
if u in self.adjList:
self.adjList[u].append((v, w))
else:
self.adjList[u] = [(v, w)]

# Assuming undirected graph
if v in self.adjList.keys():
if v in self.adjList:
self.adjList[v].append((u, w))
else:
self.adjList[v] = [(u, w)]
Expand Down
7 changes: 0 additions & 7 deletions graphs/directed_and_undirected_(weighted)_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,6 @@ def has_cycle(self):
break
else:
return True
# TODO:The following code is unreachable.
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
Expand Down Expand Up @@ -454,10 +451,6 @@ def has_cycle(self):
break
else:
return True
# TODO: the following code is unreachable
# is this meant to be called in the else ?
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
Expand Down
3 changes: 1 addition & 2 deletions hashes/hamming_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ def emitter_converter(size_par, data):
['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']
"""
if size_par + len(data) <= 2**size_par - (len(data) - 1):
print("ERROR - size of parity don't match with size of data")
exit(0)
raise ValueError("size of parity don't match with size of data")

data_out = []
parity = []
Expand Down
2 changes: 1 addition & 1 deletion linear_algebra/src/test_linear_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_zero_vector(self) -> None:
"""
test for global function zero_vector()
"""
self.assertTrue(str(zero_vector(10)).count("0") == 10)
self.assertEqual(str(zero_vector(10)).count("0"), 10)

def test_unit_basis_vector(self) -> None:
"""
Expand Down
5 changes: 3 additions & 2 deletions maths/extended_euclidean_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,12 @@ def main():
"""Call Extended Euclidean Algorithm."""
if len(sys.argv) < 3:
print("2 integer arguments required")
exit(1)
return 1
a = int(sys.argv[1])
b = int(sys.argv[2])
print(extended_euclidean_algorithm(a, b))
return 0


if __name__ == "__main__":
main()
raise SystemExit(main())
15 changes: 8 additions & 7 deletions maths/jaccard_similarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"""


def jaccard_similariy(set_a, set_b, alternative_union=False):
def jaccard_similarity(set_a, set_b, alternative_union=False):
"""
Finds the jaccard similarity between two sets.
Essentially, its intersection over union.
Expand All @@ -35,18 +35,18 @@ def jaccard_similariy(set_a, set_b, alternative_union=False):
Examples:
>>> set_a = {'a', 'b', 'c', 'd', 'e'}
>>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'}
>>> jaccard_similariy(set_a, set_b)
>>> jaccard_similarity(set_a, set_b)
0.375

>>> jaccard_similariy(set_a, set_a)
>>> jaccard_similarity(set_a, set_a)
1.0

>>> jaccard_similariy(set_a, set_a, True)
>>> jaccard_similarity(set_a, set_a, True)
0.5

>>> set_a = ['a', 'b', 'c', 'd', 'e']
>>> set_b = ('c', 'd', 'e', 'f', 'h', 'i')
>>> jaccard_similariy(set_a, set_b)
>>> jaccard_similarity(set_a, set_b)
0.375
"""

Expand All @@ -67,14 +67,15 @@ def jaccard_similariy(set_a, set_b, alternative_union=False):

if alternative_union:
union = len(set_a) + len(set_b)
return len(intersection) / union
else:
union = set_a + [element for element in set_b if element not in set_a]
return len(intersection) / len(union)

return len(intersection) / len(union)


if __name__ == "__main__":

set_a = {"a", "b", "c", "d", "e"}
set_b = {"c", "d", "e", "f", "h", "i"}
print(jaccard_similariy(set_a, set_b))
print(jaccard_similarity(set_a, set_b))
2 changes: 1 addition & 1 deletion matrix/matrix_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def add_column(self, column: list[int], position: int | None = None) -> None:
# MATRIX OPERATIONS
def __eq__(self, other: object) -> bool:
if not isinstance(other, Matrix):
raise TypeError("A Matrix can only be compared with another Matrix")
return NotImplemented
return self.rows == other.rows

def __ne__(self, other: object) -> bool:
Expand Down
4 changes: 1 addition & 3 deletions project_euler/problem_001/sol7.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ def solution(n: int = 1000) -> int:

result = 0
for i in range(n):
if i % 3 == 0:
result += i
elif i % 5 == 0:
if i % 3 == 0 or i % 5 == 0:
result += i
return result

Expand Down
11 changes: 5 additions & 6 deletions project_euler/problem_042/solution42.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,11 @@ def solution():
words = f.readline()

words = [word.strip('"') for word in words.strip("\r\n").split(",")]
words = list(
filter(
lambda word: word in TRIANGULAR_NUMBERS,
(sum(ord(x) - 64 for x in word) for word in words),
)
)
words = [
word
for word in [sum(ord(x) - 64 for x in word) for word in words]
if word in TRIANGULAR_NUMBERS
]
return len(words)


Expand Down
8 changes: 6 additions & 2 deletions project_euler/problem_067/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ def solution():
with open(triangle) as f:
triangle = f.readlines()

a = (x.rstrip("\r\n").split(" ") for x in triangle)
a = [list(map(int, x)) for x in a]
a = []
for line in triangle:
numbers_from_line = []
for number in line.strip().split(" "):
numbers_from_line.append(int(number))
a.append(numbers_from_line)

for i in range(1, len(a)):
for j in range(len(a[i])):
Expand Down
5 changes: 3 additions & 2 deletions project_euler/problem_089/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,9 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:

savings = 0

file1 = open(os.path.dirname(__file__) + roman_numerals_filename)
lines = file1.readlines()
with open(os.path.dirname(__file__) + roman_numerals_filename) as file1:
lines = file1.readlines()

for line in lines:
original = line.strip()
num = parse_roman_numerals(original)
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pandas
pillow
qiskit
requests
# scikit-fuzzy # Causing broken builds
scikit-fuzzy
sklearn
statsmodels
sympy
Expand Down
4 changes: 2 additions & 2 deletions scheduling/first_come_first_served.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,15 @@ def calculate_average_waiting_time(waiting_times: list[int]) -> float:
# ensure that we actually have processes
if len(processes) == 0:
print("Zero amount of processes")
exit()
raise SystemExit(0)

# duration time of all processes
duration_times = [19, 8, 9]

# ensure we can match each id to a duration time
if len(duration_times) != len(processes):
print("Unable to match all id's with their duration time")
exit()
raise SystemExit(0)

# get the waiting times and the turnaround times
waiting_times = calculate_waiting_times(duration_times)
Expand Down
2 changes: 1 addition & 1 deletion scheduling/multi_level_feedback_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def multi_level_feedback_queue(self) -> deque[Process]:
queue = deque([P1, P2, P3, P4])

if len(time_slices) != number_of_queues - 1:
exit()
raise SystemExit(0)

doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])})

Expand Down
2 changes: 1 addition & 1 deletion web_programming/emails_from_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def emails_from_url(url: str = "https://github.com") -> list[str]:
except ValueError:
pass
except ValueError:
exit(-1)
raise SystemExit(1)

# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
Expand Down