Skip to content
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

Misc fixes across multiple algorithms #6912

Merged
merged 13 commits into from
Oct 16, 2022
Merged
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
3 changes: 2 additions & 1 deletion data_structures/stacks/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ def test_stack() -> None:
assert not stack.is_empty()
assert stack.is_full()
assert str(stack) == str(list(range(10)))
assert stack.pop() == 9
test = stack.pop()
assert test == 9
assert stack.peek() == 8

stack.push(100)
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
4 changes: 3 additions & 1 deletion fuzzy_logic/fuzzy_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
try:
import skfuzzy as fuzz
except ImportError:
fuzz = None
import sys

sys.exit() # This is so the CI doesn't complain about an unknown library

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
11 changes: 4 additions & 7 deletions graphs/directed_and_undirected_(weighted)_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,9 @@ def has_cycle(self):
anticipating_nodes.add(node[1])
break
else:
# FIXME: there used to be unreachable code here.
# Code removed because of linter complaints.
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 @@ -453,11 +452,9 @@ def has_cycle(self):
anticipating_nodes.add(node[1])
break
else:
# FIXME: there used to be unreachable code here.
# Code removed because of linter complaints.
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
4 changes: 3 additions & 1 deletion hashes/hamming_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ def emitterConverter(sizePar, data):
"""
if sizePar + len(data) <= 2**sizePar - (len(data) - 1):
print("ERROR - size of parity don't match with size of data")
exit(0)
import sys

sys.exit(0)

dataOut = []
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_zeroVector(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_unitBasisVector(self) -> None:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/extended_euclidean_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def main():
"""Call Extended Euclidean Algorithm."""
if len(sys.argv) < 3:
print("2 integer arguments required")
exit(1)
sys.exit(1)
a = int(sys.argv[1])
b = int(sys.argv[2])
print(extended_euclidean_algorithm(a, b))
Expand Down
19 changes: 11 additions & 8 deletions maths/jaccard_similarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"""


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

>>> jaccard_similariy(setA,setA)
>>> jaccard_similarity(setA,setA)
1.0

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

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

if len(setA) == 0 or len(setB) == 0:
raise ValueError("Input must not be empty")

if isinstance(setA, set) and isinstance(setB, set):

intersection = len(setA.intersection(setB))
Expand All @@ -67,14 +70,14 @@ def jaccard_similariy(setA, setB, alternativeUnion=False):

if alternativeUnion:
union = len(setA) + len(setB)
return len(intersection) / union
else:
union = setA + [element for element in setB if element not in setA]

return len(intersection) / len(union)
return len(intersection) / len(union)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is verified, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean if it passes the tests?
Yeah, it does.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I mean the tests do go through those branches. Earlier, there was just one return statement

        return len(intersection) / len(union)

But, now the first return statement is different:

            return len(intersection) / union


if __name__ == "__main__":

setA = {"a", "b", "c", "d", "e"}
setB = {"c", "d", "e", "f", "h", "i"}
print(jaccard_similariy(setA, setB))
print(jaccard_similarity(setA, setB))
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 False
return self.rows == other.rows

def __ne__(self, other: object) -> bool:
Expand Down
3 changes: 2 additions & 1 deletion other/lfu_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,8 @@ def set(self, key: T, value: U) -> None:
# explain to type checker via assertions
assert first_node is not None
assert first_node.key is not None
assert self.list.remove(first_node) is not None
remove_test = self.list.remove(first_node)
assert remove_test is not None
# first_node guaranteed to be in list

del self.cache[first_node.key]
Expand Down
3 changes: 2 additions & 1 deletion other/lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,9 @@ def set(self, key: T, value: U) -> None:
# explain to type checker via assertions
assert first_node is not None
assert first_node.key is not None
test_removal = self.list.remove(first_node)
assert (
self.list.remove(first_node) is not None
test_removal is not None
) # node guaranteed to be in list assert node.key is not None

del self.cache[first_node.key]
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
13 changes: 6 additions & 7 deletions project_euler/problem_042/solution42.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ def solution():
with open(wordsFilePath) as f:
words = f.readline()

words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(",")))
words = list(
filter(
lambda word: word in TRIANGULAR_NUMBERS,
map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words),
)
)
words = [word.strip('"') for word in words.strip("\r\n").split(",")]
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
4 changes: 2 additions & 2 deletions project_euler/problem_067/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def solution():
with open(triangle) as f:
triangle = f.readlines()

a = map(lambda x: x.rstrip("\r\n").split(" "), triangle)
a = list(map(lambda x: list(map(int, x)), a))
a = [x.rstrip("\r\n").split(" ") for x in triangle]
a = [[int(i) for i in x] for x in a]

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
3 changes: 2 additions & 1 deletion project_euler/problem_099/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ def solution(data_file: str = "base_exp.txt") -> int:
largest: float = 0
result = 0
for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))):
a, x = list(map(int, line.split(",")))
a, x = line.split(",")
a, x = int(a), int(x)
if x * log10(a) > largest:
largest = x * log10(a)
result = i + 1
Expand Down
6 changes: 4 additions & 2 deletions scheduling/first_come_first_served.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,21 +73,23 @@ def calculate_average_waiting_time(waiting_times: list[int]) -> float:


if __name__ == "__main__":
import sys

# process id's
processes = [1, 2, 3]

# ensure that we actually have processes
if len(processes) == 0:
print("Zero amount of processes")
exit()
sys.exit()

# 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()
sys.exit()

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

if len(time_slices) != number_of_queues - 1:
exit()
import sys

sys.exit()

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

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

sys.exit(-1)

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