Skip to content

Commit 0d115a6

Browse files
committed
Misc fixes
@dhruvmanila told me to commit these here so here we go Fixes TheAlgorithms#6916 among other issues
1 parent 61547f4 commit 0d115a6

File tree

21 files changed

+57
-46
lines changed

21 files changed

+57
-46
lines changed

compression/huffman.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def parse_file(file_path: str) -> list[Letter]:
3131
c = f.read(1)
3232
if not c:
3333
break
34-
chars[c] = chars[c] + 1 if c in chars.keys() else 1
34+
chars[c] = chars[c] + 1 if c in chars else 1
3535
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
3636

3737

data_structures/linked_list/is_palindrome.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def is_palindrome_dict(head):
5555
d = {}
5656
pos = 0
5757
while head:
58-
if head.val in d.keys():
58+
if head.val in d:
5959
d[head.val].append(pos)
6060
else:
6161
d[head.val] = [pos]

data_structures/stacks/stack.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ def test_stack() -> None:
110110
assert not stack.is_empty()
111111
assert stack.is_full()
112112
assert str(stack) == str(list(range(10)))
113-
assert stack.pop() == 9
113+
test = stack.pop()
114+
assert test == 9
114115
assert stack.peek() == 8
115116

116117
stack.push(100)

fuzzy_logic/fuzzy_operations.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
try:
1313
import skfuzzy as fuzz
1414
except ImportError:
15-
fuzz = None
15+
import sys
16+
sys.exit() # This is so the CI doesn't complain about an unknown library
1617

1718
if __name__ == "__main__":
1819
# Create universe of discourse in Python using linspace ()

graphs/dijkstra_algorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,13 @@ def add_edge(self, u, v, w):
8989
# Edge going from node u to v and v to u with weight w
9090
# u (w)-> v, v (w) -> u
9191
# Check if u already in graph
92-
if u in self.adjList.keys():
92+
if u in self.adjList:
9393
self.adjList[u].append((v, w))
9494
else:
9595
self.adjList[u] = [(v, w)]
9696

9797
# Assuming undirected graph
98-
if v in self.adjList.keys():
98+
if v in self.adjList:
9999
self.adjList[v].append((u, w))
100100
else:
101101
self.adjList[v] = [(u, w)]

graphs/directed_and_undirected_(weighted)_graph.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -225,10 +225,9 @@ def has_cycle(self):
225225
anticipating_nodes.add(node[1])
226226
break
227227
else:
228+
# FIXME: there used to be unreachable code here.
229+
# Code removed because of linter complaints.
228230
return True
229-
# TODO:The following code is unreachable.
230-
anticipating_nodes.add(stack[len_stack_minus_one])
231-
len_stack_minus_one -= 1
232231
if visited.count(node[1]) < 1:
233232
stack.append(node[1])
234233
visited.append(node[1])
@@ -453,11 +452,9 @@ def has_cycle(self):
453452
anticipating_nodes.add(node[1])
454453
break
455454
else:
455+
# FIXME: there used to be unreachable code here.
456+
# Code removed because of linter complaints.
456457
return True
457-
# TODO: the following code is unreachable
458-
# is this meant to be called in the else ?
459-
anticipating_nodes.add(stack[len_stack_minus_one])
460-
len_stack_minus_one -= 1
461458
if visited.count(node[1]) < 1:
462459
stack.append(node[1])
463460
visited.append(node[1])

hashes/hamming_code.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,9 @@ def emitterConverter(sizePar, data):
8080
"""
8181
if sizePar + len(data) <= 2**sizePar - (len(data) - 1):
8282
print("ERROR - size of parity don't match with size of data")
83-
exit(0)
83+
import sys
84+
85+
sys.exit(0)
8486

8587
dataOut = []
8688
parity = []

linear_algebra/src/test_linear_algebra.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_zeroVector(self) -> None:
8989
"""
9090
test for global function zero_vector()
9191
"""
92-
self.assertTrue(str(zero_vector(10)).count("0") == 10)
92+
self.assertEqual(str(zero_vector(10)).count("0"), 10)
9393

9494
def test_unitBasisVector(self) -> None:
9595
"""

maths/extended_euclidean_algorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def main():
7575
"""Call Extended Euclidean Algorithm."""
7676
if len(sys.argv) < 3:
7777
print("2 integer arguments required")
78-
exit(1)
78+
sys.exit(1)
7979
a = int(sys.argv[1])
8080
b = int(sys.argv[2])
8181
print(extended_euclidean_algorithm(a, b))

maths/jaccard_similarity.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""
1515

1616

17-
def jaccard_similariy(setA, setB, alternativeUnion=False):
17+
def jaccard_similarity(setA, setB, alternativeUnion=False):
1818
"""
1919
Finds the jaccard similarity between two sets.
2020
Essentially, its intersection over union.
@@ -35,21 +35,24 @@ def jaccard_similariy(setA, setB, alternativeUnion=False):
3535
Examples:
3636
>>> setA = {'a', 'b', 'c', 'd', 'e'}
3737
>>> setB = {'c', 'd', 'e', 'f', 'h', 'i'}
38-
>>> jaccard_similariy(setA,setB)
38+
>>> jaccard_similarity(setA,setB)
3939
0.375
4040
41-
>>> jaccard_similariy(setA,setA)
41+
>>> jaccard_similarity(setA,setA)
4242
1.0
4343
44-
>>> jaccard_similariy(setA,setA,True)
44+
>>> jaccard_similarity(setA,setA,True)
4545
0.5
4646
4747
>>> setA = ['a', 'b', 'c', 'd', 'e']
4848
>>> setB = ('c', 'd', 'e', 'f', 'h', 'i')
49-
>>> jaccard_similariy(setA,setB)
49+
>>> jaccard_similarity(setA,setB)
5050
0.375
5151
"""
5252

53+
if len(setA) == 0 or len(setB) == 0:
54+
raise ValueError("Input must not be empty")
55+
5356
if isinstance(setA, set) and isinstance(setB, set):
5457

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

6871
if alternativeUnion:
6972
union = len(setA) + len(setB)
73+
return len(intersection) / union
7074
else:
7175
union = setA + [element for element in setB if element not in setA]
72-
73-
return len(intersection) / len(union)
76+
return len(intersection) / len(union)
7477

7578

7679
if __name__ == "__main__":
7780

7881
setA = {"a", "b", "c", "d", "e"}
7982
setB = {"c", "d", "e", "f", "h", "i"}
80-
print(jaccard_similariy(setA, setB))
83+
print(jaccard_similarity(setA, setB))

matrix/matrix_class.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ def add_column(self, column: list[int], position: int | None = None) -> None:
286286
# MATRIX OPERATIONS
287287
def __eq__(self, other: object) -> bool:
288288
if not isinstance(other, Matrix):
289-
raise TypeError("A Matrix can only be compared with another Matrix")
289+
return False
290290
return self.rows == other.rows
291291

292292
def __ne__(self, other: object) -> bool:

other/lfu_cache.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,8 @@ def set(self, key: T, value: U) -> None:
264264
# explain to type checker via assertions
265265
assert first_node is not None
266266
assert first_node.key is not None
267-
assert self.list.remove(first_node) is not None
267+
remove_test = self.list.remove(first_node)
268+
assert remove_test is not None
268269
# first_node guaranteed to be in list
269270

270271
del self.cache[first_node.key]

other/lru_cache.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,9 @@ def set(self, key: T, value: U) -> None:
280280
# explain to type checker via assertions
281281
assert first_node is not None
282282
assert first_node.key is not None
283+
test_removal = self.list.remove(first_node)
283284
assert (
284-
self.list.remove(first_node) is not None
285+
test_removal is not None
285286
) # node guaranteed to be in list assert node.key is not None
286287

287288
del self.cache[first_node.key]

project_euler/problem_001/sol7.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ def solution(n: int = 1000) -> int:
2626

2727
result = 0
2828
for i in range(n):
29-
if i % 3 == 0:
30-
result += i
31-
elif i % 5 == 0:
29+
if i % 3 == 0 or i % 5 == 0:
3230
result += i
3331
return result
3432

project_euler/problem_042/solution42.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,12 @@ def solution():
3333
with open(wordsFilePath) as f:
3434
words = f.readline()
3535

36-
words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(",")))
37-
words = list(
38-
filter(
39-
lambda word: word in TRIANGULAR_NUMBERS,
40-
map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words),
41-
)
42-
)
36+
words = [word.strip('"') for word in words.strip("\r\n").split(",")]
37+
words = [
38+
word
39+
for word in [sum(ord(x) - 64 for x in word) for word in words]
40+
if word in TRIANGULAR_NUMBERS
41+
]
4342
return len(words)
4443

4544

project_euler/problem_067/sol1.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def solution():
2828
with open(triangle) as f:
2929
triangle = f.readlines()
3030

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

3434
for i in range(1, len(a)):
3535
for j in range(len(a[i])):

project_euler/problem_089/sol1.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,9 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
125125

126126
savings = 0
127127

128-
file1 = open(os.path.dirname(__file__) + roman_numerals_filename)
129-
lines = file1.readlines()
128+
with open(os.path.dirname(__file__) + roman_numerals_filename) as file1:
129+
lines = file1.readlines()
130+
130131
for line in lines:
131132
original = line.strip()
132133
num = parse_roman_numerals(original)

project_euler/problem_099/sol1.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ def solution(data_file: str = "base_exp.txt") -> int:
2525
largest: float = 0
2626
result = 0
2727
for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))):
28-
a, x = list(map(int, line.split(",")))
28+
a, x = line.split(",")
29+
a, x = int(a), int(x)
2930
if x * log10(a) > largest:
3031
largest = x * log10(a)
3132
result = i + 1

scheduling/first_come_first_served.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -73,21 +73,23 @@ def calculate_average_waiting_time(waiting_times: list[int]) -> float:
7373

7474

7575
if __name__ == "__main__":
76+
import sys
77+
7678
# process id's
7779
processes = [1, 2, 3]
7880

7981
# ensure that we actually have processes
8082
if len(processes) == 0:
8183
print("Zero amount of processes")
82-
exit()
84+
sys.exit()
8385

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

8789
# ensure we can match each id to a duration time
8890
if len(duration_times) != len(processes):
8991
print("Unable to match all id's with their duration time")
90-
exit()
92+
sys.exit()
9193

9294
# get the waiting times and the turnaround times
9395
waiting_times = calculate_waiting_times(duration_times)

scheduling/multi_level_feedback_queue.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,9 @@ def multi_level_feedback_queue(self) -> deque[Process]:
276276
queue = deque([P1, P2, P3, P4])
277277

278278
if len(time_slices) != number_of_queues - 1:
279-
exit()
279+
import sys
280+
281+
sys.exit()
280282

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

web_programming/emails_from_url.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ def emails_from_url(url: str = "https://github.com") -> list[str]:
9393
except ValueError:
9494
pass
9595
except ValueError:
96-
exit(-1)
96+
import sys
97+
98+
sys.exit(-1)
9799

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

0 commit comments

Comments
 (0)